<?php 
/**
 * @author :NGHIAT
 * @since : 22/10/2010
 * @see : Lop chua cac phuong thuc dung chung cho toan bo cac modul
 *@copyright :EFY VIET NAM JSC
 */ 
 class Efy_Function_RecordFunctions{
 
	public function DocSentAttachFile($arrFileList, $piCountFile, $piMaxNumberAttachFile = 10, $psHaveUpLoadFields = true, $size,$fileName ='FileName'){		
		$tr_line_new = 'tr_line_new';
		$tr_line_exist = 'tr_line_exist'; 
		$chk_file_attach_new_id = 'chk_file_attach_new_id';
		$chk_file_attach_exist_id = 'chk_file_attach_exist_id';
		$hdn_deleted_new_file_id_list = 'hdn_deleted_new_file_id_list'; 
		$delete_row_exist = 'delete_row_exist';
		if($fileName <>'FileName'){
			//echo "<br>ccc<br>";exit;
			$tr_line_new = $tr_line_new.$fileName;
			$tr_line_exist = $tr_line_exist.$fileName; 
			$chk_file_attach_new_id = $chk_file_attach_new_id.$fileName;
			$chk_file_attach_exist_id = $chk_file_attach_exist_id.$fileName;
			$hdn_deleted_new_file_id_list = $hdn_deleted_new_file_id_list.$fileName; 
			$delete_row_exist = $delete_row_exist.$fileName;
		}
		$psGotoUrlForDeleteFile = "javascript:delete_row(document.getElementsByName(\"$tr_line_new\"),document.getElementsByName(\"$chk_file_attach_new_id\"),document.getElementById(\"$hdn_deleted_new_file_id_list\"));";
		$psGotoUrlForAddFile = "javascript:add_row(document.getElementsByName(\"$tr_line_new\")," . $piMaxNumberAttachFile .");";
		$strHTML = $strHTML . "<table width='75%' cellpadding='0' cellspacing='0'><col width = '6%'><col width = '94%'>";	
		//Tao doi tuong thong tin config
		$objConfig = new Efy_Init_Config();
		//ID File dinh kem		
		if (($piCountFile>0) && ($arrFileList != '')){		
			// Goi thu tuc xu ly khi xoa cac file da co
			$psGotoUrlForDeleteFile = $psGotoUrlForDeleteFile . "delete_row_exist(document.getElementsByName(\"$tr_line_exist\"),document.getElementsByName(\"$chk_file_attach_exist_id\"),\"" . $_SERVER['REQUEST_URI'] . "\");";
			for ($index = 0; $index<$piCountFile; $index++){
				$sFileId = $arrFileList[$index]['PK_FILE'];
				$sFileName = $arrFileList[$index]['C_FILE_NAME']; 
				// Tach ten file ra
				if(strpos($sFileName,"!~!") == 0){
					$file_name = $sFileName;
				}else{
					$arrFilename = explode('!~!',$sFileName);					
					$file_name = $arrFilename[1];
					$file_id   = explode("_", $arrFilename[0]);
				}							
				//Get URL
				$sActionUrl = $objConfig->_setAttachFileUrlPath() . $file_id[0] . "/" . $file_id[1] . "/" . $file_id[2] . "/" . $sFileName;		
				
				//
				$strHTML = $strHTML . "<tr id='$tr_line_exist' name = '$tr_line_exist'><td colspan='2' class='normal_link'>";
				if ($psHaveUpLoadFields){
					$strHTML = $strHTML . "<input type='checkbox' name='$chk_file_attach_exist_id' id = '' value='$sFileName'>";				
				}
				$strHTML = $strHTML . "<a href='$sActionUrl' $target > $file_name  </a></td></tr>";
			}
		}		
		//Them moi
		if ($psHaveUpLoadFields){
			//Vong lap hien thi cac file dinh kem se them vao van ban
			for($index = 0; $index<$piMaxNumberAttachFile; $index++){					
				if ($index < 1 ) {
					$v_str_show="block";
				}else{
					$v_str_show="none";
				}
				$strHTML = $strHTML . "<tr name = '$tr_line_new' id='$tr_line_new' style='display:$v_str_show'><td><input type='checkbox' name='$chk_file_attach_new_id' id = '$chk_file_attach_new_id' value=$index></td>";
				$strHTML = $strHTML . "<td><input class='textbox' type='file' name='$fileName$index' id = '$fileName$index' optional='true' size = '" . $size . "'></td></tr>";
			}	
			$strHTML = $strHTML . "<tr align='center'><td colspan='2' align='center'><a onclick='$psGotoUrlForAddFile' class='small_link'>Th&#234;m file</a>&nbsp;|&nbsp;";
			$strHTML = $strHTML . "	<a onclick='$psGotoUrlForDeleteFile' class='small_link'>X&#243;a file</a></td></tr>";
		}
		$strHTML = $strHTML . "</table>";
		//echo htmlspecialchars($strHTML);//exit;
		return $strHTML;
	}	
	/*
	 * Creater : phongtd
 	 * Date : 18/09/2009
 	 * Idea : Ham tao chuoi HTML sinh ra danh sach cac multiple_checkbox cua cac DON VI
	 *
	 * @param unknown_type $arrUnit
	 * @param unknown_type $unitIdList
	 * @return Danh sach cac multiple_checkbox cua cac DON VI
	 */
	public function DocGenerateMultipleCheckbox($arrUnit, $unitIdList = "", $TagName = "ds_don_vi"){
		$strHTML ="";
		$strHTML = $strHTML . "<tr><td colspan='10' style='display:none;'><input type='text' id = '$TagName' name='$TagName' value='' hide='true'  xml_data='true' xml_tag_in_db='$TagName' optional='true' message=''></td></tr>";		
		//Dat style cho cac row
		$v_current_style_name == "round_row";
		
		//Duyet cac phan tu mang danh sach DON VI 			
		for($i = 0; $i<sizeof($arrUnit); $i++){				
			//Checked gia tri
			$sChecked = "";
			//Kiem tra xem Hieu chinh hay la them moi
			if(trim($unitIdList) != ""){
				//Danh sach Id DON VI luu trong CSDL
				$arrUnitInDb = explode(",",$unitIdList);
				for ($index = 0;$index < sizeof($arrUnitInDb);$index++){
					if ($arrUnitInDb[$index] == $arrUnit[$i]['id']){
						$sChecked = "checked";
					}
				}
			}			
			$unitId = $arrUnit[$i]['id'];
			if($i % 2 == 0 ){
				if ($v_current_style_name == "round_row"){
					$v_current_style_name = "odd_row";
				}else{
					$v_current_style_name = "round_row";
				}				
				$strHTML = $strHTML. "<tr class='" . $v_current_style_name . "'>";				
			}			
			$strHTML = $strHTML. "<td><input $sChecked  type='checkbox' id='chk_multiple_checkbox' name='chk_multiple_checkbox'  xml_data='true' optional = 'true' value='$unitId'  xml_tag_in_db_name ='$TagName'  nameUnit = '" . $arrUnit[$i]['name'] . "'>" . $arrUnit[$i]['name'] . "</td>";			
			if($i % 2 <> 0 ){				
				$strHTML = $strHTML. "</tr>";	
			}			
		}   
		return $strHTML;
	}
	
	/**
 	 * Creater : phongtd
 	 * Date : 02/10/2009
 	 * Idea : Ham tao chuoi HTML lay ra danh sach cac checkbox LANH DAO 
 	 * @param  $arrLeader
 	 * @param  $leaderIdList
 	 * @return Danh sach cac checkbox LANH DAO 
 	 */
	public function docGenerateLeaderList($arrLeader, $leaderIdList = "" ){
		$strHTML ="";	
		$strHTML .= $this->formHidden("ds_lanh_dao","",array("xml_data"=>"true", "optional" =>"true", "xml_tag_in_db"=>"ds_lanh_dao"));
		//Duyet cac phan tu mang danh sach LANH DAO DON VI 	
		for($i = 0; $i<sizeof($arrLeader); $i++){				
			//Checked gia tri
			$sChecked = "";
			//Kiem tra xem Hieu chinh hay la them moi
			if(trim($leaderIdList) != ""){			
				//Danh sach Id Lanh dao luu trong CSDL
				$arrLeaderInDb = explode(",",$leaderIdList);											
				for ($index = 0;$index < sizeof($arrLeaderInDb);$index++){
					if ($arrLeaderInDb[$index] == $arrLeader[$i]['id']){
						$sChecked = "checked";
					}
				}
			}	
			$leaderId = $arrLeader[$i]['id'];
			$strHTML = $strHTML. "<tr>";			
			$strHTML = $strHTML. "<td><input $sChecked type='checkbox' id='chk_multiple' name='chk_multiple'  xml_data='false' optional = 'true' value='$leaderId'  xml_tag_in_db_name ='' >".$arrLeader[$i]['position_name'].' - '. $arrLeader[$i]['name']."</td></tr>";			
		}   
		return $strHTML;					
	}
	  /**
	 * Creater : phongtd
	 * Date : 20/05/2010
	 * Idea : Tim kiem gia tri trong mot mang   
	 *
	 * @param $arrRes : Mang gia tri
	 * @param $ColumnIdRes : Ma gia tri
	 * @param $ColumnTexRes : Ten gia tri
	 * @param $TextRes : Gia tri tim kiem
	 * @param $hndRes : Hidden luu gia tri
	 * @param $editable : 1 : duoc phep them moi doi tuong, 0: khong duoc phep them moi doi tuong
	 * @param $option : (Neu $option = 1 chi chon mot doi tuong ; $option = 0 thi duoc chon nhieu)
	 * @param $sColumName : Cot du lieu can bo sung them vao text hien thi tren doi tuong Auto Complete Text (vi du: truyen vao gia tri position_code hien thi Ma chuc vu - Ten can b. CT - Nguyen Van A)
	 * @param $disOpt: 1: hien thi C_CODE, 2: hien thi C_NAME (chi dung trong truong hop $editable = 0)
	 * @param $fs,$fc,$fd : Tuong ung la cac ham fSelect, fClear, fDelete
	 * @return Xau html 
	 * $defineFun : Ham se thuc thi khi NSD chon mot gia tri trong autocomplete textbox
	 */
	 function doc_search_ajax($arrRes, $ColumnIdRes, $ColumnTexRes, $TextRes,$hndRes,$single = 1,$sColumName = "",$editable = 0,$disOpt = 0,$fs = "",$fc = "",$fd = ""){
		$sWebsitePart = Efy_Init_Config::_setWebSitePath();
		$sHtmlRes = '';
		$sHtmlRes = $sHtmlRes . ' <script type="text/javascript">  ';//
		$sHtmlNameId = '';
		$sHtmlNameId = $sHtmlNameId. '  var NameID'.$hndRes.' = new Array(' ;//
		$sHtmlNameText = '';
		$sHtmlNameText = $sHtmlNameText . ' var NameText'.$hndRes.' = new Array(';
		$sHtmlNameStr = '';
		$sHtmlNameStr .= ' var NameStr'.$hndRes.' = new Array(';							
		// Ghi Ma va ten ra mot mang
		foreach($arrRes as $arrTemp){
			$sTemp = "";
			if ($sColumName != ""){
				$sPositionCode = $arrTemp[$sColumName];
				if ($sPositionCode != ""){
					$sTemp = $sPositionCode . " - ";
				}
			}	
			$sHtmlNameId = $sHtmlNameId .'"' . $arrTemp[$ColumnIdRes] . '",' ;
			$sHtmlNameText = $sHtmlNameText .'"' . $sTemp . str_replace('"', '\"', $arrTemp[$ColumnTexRes]) . '",' ;
			if($disOpt == 2)				
				$sHtmlNameStr .= '"' . $arrTemp[$ColumnTexRes] . '",' ;			 
		}
		$sHtmlNameId = rtrim($sHtmlNameId,',') . '); ';
		$sHtmlNameText = rtrim($sHtmlNameText,',') . '); ';
		$sHtmlNameStr = rtrim($sHtmlNameStr,',') . '); ';		
		$sHtmlRes = $sHtmlRes . $sHtmlNameId . $sHtmlNameText.$sHtmlNameStr . ' ';		
		$sHtmlRes = $sHtmlRes .' obj'.$hndRes.' = new actb(document.getElementById(\''.$TextRes.'\'),document.getElementById(\''.$hndRes.'\'),NameStr'.$hndRes.',NameText'.$hndRes.',NameID'.$hndRes.',\'FillProduct('.$disOpt.',\',\''.$single.'\',\''.$editable.'\',\''.$sWebsitePart.'\',\''.$fs.'\',\''.$fc.'\',\''.$fd.'\');';
		$sHtmlRes = $sHtmlRes . '</script>';
		return  $sHtmlRes;
		
	}
	  /**
	 * Creater : nghiat
	 * Date : 07/06/2010
	 * Idea : Lay ngay dau tien trong tuan
	 *
	 * @return Ngay dau tuan 
	 */
	
	function getFirstDayOfWeek($format = ""){
		$firstDayOfWeek = "";
		$currentWeek = date("W"); // thu tu tuan hien tai cua nam
		$currentYear = date("Y"); // nam hien tai
		$orderDate = 0; // xac dinh ngay dau tuan (thu 2)
		$firstDayOfWeek = Efy_Library::_getAnyDateOnWeekOfYear($currentYear,$currentWeek,$orderDate);
		return $firstDayOfWeek;
	}	
	/**
	 * Nguoi tạo: Phongtd
	 * Ngay tao: 22/06/2010
	 * Lay ra danh sach Ten + Chuc vu tu danh sach Id staff
	 */
	public function getNamePositionStaffByIdList($sStaffIdList,$delimitor = '!#~$|*'){
		$arrStaffId = explode(',',$sStaffIdList);
		$sNamePositionStaffList= "";
		for($i=0;$i< sizeof($arrStaffId);$i++){  
			$sName = Efy_Publib_Library ::_getItemAttrById($_SESSION['arr_all_staff'],$arrStaffId[$i],'name');  
			$sPosition = Efy_Publib_Library ::_getItemAttrById($_SESSION['arr_all_staff'],$arrStaffId[$i],'position_code');
	    	$sNamePositionStaffList = $sNamePositionStaffList .$delimitor. $sPosition . ' - ' . $sName;
	    }       
	    $sNamePositionStaffList = substr($sNamePositionStaffList,6); 
		return $sNamePositionStaffList;		
	}
	
	/**
	 * Nguoi tạo: Phongtd
	 * Ngay tao: 22/06/2010
	 * Lay ra danh sach Ten phong ban tu danh sach Id phong ban
	 */
	public function getNameUnitByIdUnitList($sUnitIdList){
		$arrUnitId = explode(',',$sUnitIdList);
		$sNameUnitList= "";
		for($i=0;$i< sizeof($arrUnitId);$i++){  
			$sNameUnit = Efy_Publib_Library ::_getItemAttrById($_SESSION['arr_all_unit'],$arrUnitId[$i],'name');  
	    	$sNameUnitList = $sNameUnitList .'!#~$|*'. $sNameUnit;
	    }       
	    $sNameUnitList = substr($sNameUnitList,6); 
		return $sNameUnitList;		
	}
	
	/**
	 * Creater : HUNGVM
	 * Date : 25/06/2010
	 * Idea : Tao phuong thuc chuyen doi danh sach ten can bo thanh ID tuong ung
	 *
	 * @param $sStaffNameList : Chuoi luu danh sach ten can bo (phan tach boi dau ';')
	 * @return Danh sach ID can bo tuong ung voi list name
	 */
	public function convertStaffNameToStaffId($sStaffNameList = "",$delimitor =","){
		$sStaffIdList = "";
		if (trim($sStaffNameList) != ""){
			//chuyen doi mang danh sach ten can bo ra mang mot chieu
			$arr_staff_name = explode(";",$sStaffNameList);
			for ($index = 0; $index<sizeof($arr_staff_name); $index++){
				foreach($_SESSION['arr_all_staff_keep'] as $staff){
					$sStaffPositionName = $staff['position_code'] . " - " . $staff['name'];
					if (trim($sStaffPositionName) == trim($arr_staff_name[$index])){
						$sStaffIdList .= $staff['id'] . $delimitor;
					}
				}
			}	
			$sStaffIdList = substr($sStaffIdList,0,strlen($sStaffIdList)-1); 
		}
		return $sStaffIdList;
	}
	
	/**
	 * Creater : Phongtd
	 * Date : 30/06/2010
	 * Idea : Tao phuong thuc chuyen doi danh sach ten phong ban thanh ID tuong ung
	 *
	 * @param $sUnitNameList : Chuoi luu danh sach ten phong ban (phan tach boi dau ';')
	 * @return Danh sach ID phong ban tuong ung voi list name
	 */
	public  function convertUnitNameListToUnitIdList($sUnitNameList = ""){
		$sUnitIdList = "";
		if (trim($sUnitNameList) != ""){
			//chuyen doi mang danh sach ten can bo ra mang mot chieu
			$arrUnitName = explode(";",$sUnitNameList);
			//var_dump($arrUnitName); exit;
			for ($index = 0; $index<sizeof($arrUnitName); $index++){
				foreach($_SESSION['arr_all_unit_keep'] as $unit){
					if (trim($unit['name']) == trim($arrUnitName[$index])){
						$sUnitIdList .= $unit['id'] . ";";
					}
				}
			}	
			$sUnitIdList = substr($sUnitIdList,0,-1); 
		}
		return $sUnitIdList;
	}
	/**
	 * Creater : Phongtd
	 * Date : 20/07/2010
	 * Idea : Lay danh sach can bo cua phong ban
	 * @param $iDepartmentId: ID cua phong can lay
	 * @return Mang chu danh sach can bo cua 1 phong ban
	 */
	function docGetAllDepartmentStaffId($iDepartmentId){
		$i = 0;
		foreach($_SESSION['arr_all_staff_keep'] as $staffId){	
			if ($staffId['unit_id'] == $iDepartmentId){
				$arrDepartmentStaffId[$i] =  $staffId;
				$i++;
			}
		}
		return $arrDepartmentStaffId;	
	}
	/**
	 * Creater : nghiat
	 * Date : 03/08/2010
	 * Idea : Lay danh sach can bo cua phong ban
	 * @param $positionGroupCode: Nhom lanh dao, $unitID ID phong ban hoac VP, UB
	 * @return Mang chu danh sach lanh dao cua mot phong, ban
	 */
	function docGetAllLeaderDepartment($positionGroupCode,$iDepartmentId){
		$k = 0;
		foreach($_SESSION['arr_all_staff_keep'] as $staffId){	
			if ($staffId['unit_id'] == $iDepartmentId and $staffId['position_group_code'] ==$positionGroupCode ){
				$arrDepartmentStaffId[$k] =  $staffId;
				$k++;
			}
		}
		return $arrDepartmentStaffId;	
	}
	/**
	 * Creater : nghiat
	 * Date : 04/08/2010
	 * Idea : Lay nguoi ky cua don vi dang nhap hien thoi
	 * @param $arrSigner: mang nguoi ky cua DANH_MUC_NGUOI_KY
	 * @return $arrResult
	 */
	function docGetSignByUnit($arrSigner){
		$j = 0; $m = 0;
		$arr_all_staff = $_SESSION['arr_all_staff'];
		for ($i=0;$i<sizeof($arrSigner);$i++){	
			for ($m=0;$m<sizeof($arr_all_staff);$m++)	{	
				if ($arrSigner[$i]['C_CODE'] == $arr_all_staff[$m]['id']){
					$arrResult[$j]['C_CODE'] = $arrSigner[$i]['C_CODE'];
					$arrResult[$j]['C_NAME'] = $arrSigner[$i]['C_NAME'];
					$j ++;
					$m = sizeof($arr_all_staff);
				}
			}	
		}
		return $arrResult;
	}
	function _get_item_attr_by_id($p_array, $p_id, $p_attr_name) {
		foreach($p_array as $staff){
			if (strcasecmp($staff['id'],$p_id)==0){
				return $staff[$p_attr_name];
			}
		}
		return "";
	}
	/**
	 * Phongtd
	 * Ham lay danh sach id phong ban tu danh sach id can bo
	 * @param unknown_type $v_staff_id_list
	 * @param unknown_type $v_option
	 * @return unknown
	 */
	function doc_get_all_unit_permission_form_staffIdList($v_staff_id_list,$v_option = 'unit'){
		$arr_staff_id = explode(',',$v_staff_id_list);
		$v_return_string = "";
		if($v_option == 'unit'){
			for($i=0;$i< sizeof($arr_staff_id);$i ++){
				$v_return_string = $v_return_string . ',' . Efy_Function_RecordFunctions::_get_item_attr_by_id($_SESSION['arr_all_staff_keep'], $arr_staff_id[$i],'unit_id');
			}
			$v_return_string = substr($v_return_string,1);
		}
		return $v_return_string;
		}

	/**
	* Nguoi tao: PHUONGTT
	* Ngay tao: 13/10/2011
	* Y nghia:Lay Mang danh muc doi tuong cua mot danh muc
	* Input: Ma danh muc
	* Output: Mang cac doi tuong cua loai danh muc ung voi ma truyen vao 
	* $sOwnerCode: Mã đơn vị sử dụng
	* $sCode: Mã loại hồ sơ TTHC
	* $sProvince: Mã tỉnh/TP
	*/
	public static function getAllObjectbyListCode($sOwnerCode,$sCode,$sProvince = "")
	{ 
		$sOwnerCode ='';
		$arrXmlData = array();
		$sFilePath = Efy_Init_Config::_setXmlFileUrlPath(1) . "list/output/$sCode.xml";
		if ($sOwnerCode != ""){
			$sFilePath = Efy_Init_Config::_setXmlFileUrlPath(1) . "list/output/".$sOwnerCode."/$sCode.xml";
		}
		$objXmlData = new Zend_Config_Xml($sFilePath,'data_list');
		if (isset($objXmlData->item)){
			$arrXmlData = $objXmlData->item->toArray();
		}		
		//var_dump($arrXmlData);exit;
		$arrOutput = array();
		if (isset($arrXmlData[0]) && is_array($arrXmlData[0])){
			foreach($arrXmlData as $value){
				if ($sOwnerCode != ''){
					$arrOwnerCode = explode(',',$value['c_owner_code']);
					if(in_array($sOwnerCode,$arrOwnerCode)){						
						if ($sProvince != ""){//Tinh/thanh pho
							if (trim($value['tinh_thanh']) == $sProvince){
								array_push($arrOutput,array('C_CODE'=>$value['c_code'],'C_NAME'=>$value['c_name'],'C_STATUS'=>$value['c_status']));
							}	
						}else{
							array_push($arrOutput,array('C_CODE'=>$value['c_code'],'C_NAME'=>$value['c_name'],'C_STATUS'=>$value['c_status']));
						}	
					}
				}else {					
					if ($sProvince != ""){//Tinh/thanh pho
						if (trim($value['tinh_thanh']) == $sProvince){
							array_push($arrOutput,array('C_CODE'=>$value['c_code'],'C_NAME'=>$value['c_name'],'C_STATUS'=>$value['c_status']));
						}	
					}else{
						array_push($arrOutput,array('C_CODE'=>$value['c_code'],'C_NAME'=>$value['c_name'],'C_STATUS'=>$value['c_status']));
					}		
				}
			}
		}else{
			array_push($arrOutput,array('C_CODE'=>$arrXmlData['c_code'],'C_NAME'=>$arrXmlData['c_name'],'C_STATUS'=>$arrXmlData['c_status']));
		}
		return $arrOutput;
	}
 	/**
	* Nguoi tao: PHUONGTT
	* Ngay tao: 13/10/2011
	* Y nghia:Lay Mang tat ca thong tin danh muc doi tuong cua mot danh muc
	* Input: Ma danh muc
	* Output: Mang cac doi tuong cua loai danh muc ung voi ma truyen vao 
	*/
	public static function getAllObjectbyListCodeFull($sOwnerCode,$sCode)
	{ 
		$sOwnerCode ='';
		try {
			$Efy_Init_Config = new Efy_Init_Config(); $arrOutput = array(); $arrXmlData = array();
			$sFilePath = $Efy_Init_Config->_setXmlFileUrlPath(1) . "list/output/$sCode.xml";			
			if ($sOwnerCode!=""){
				$sFilePath = $Efy_Init_Config->_setXmlFileUrlPath(1) . "list/output/" . $sOwnerCode . "/$sCode.xml";
			}			
			if (!file_exists($sFilePath)){
				return $arrOutput;
			}							
			$objXmlData = new Zend_Config_Xml($sFilePath,'data_list');			
			//Kiểm tra tồn tại phần mềm 'item' trong file XML không?
			if (isset($objXmlData->item)){
				$arrXmlData = $objXmlData->item->toArray();
			}
			if (isset($arrXmlData[0]) && is_array($arrXmlData[0])){
				$arrayKey = array_keys($arrXmlData[0]);
				foreach($arrXmlData as $value){
					if ($sOwnerCode != ''){
						$arrOwnerCode = explode(',',$value['c_owner_code']);
						if(in_array($sOwnerCode,$arrOwnerCode)){
							$arrTemp = array();
							foreach ($arrayKey as $value1){
								$key = strtoupper($value1);
								$arrTemp[$key] = $value[$value1];
							}
							array_push($arrOutput,$arrTemp);
						}
					}else {
						$arrTemp = array();
						foreach ($arrayKey as $value1){
							$key = strtoupper($value1);
							$arrTemp[$key] = $value[$value1];
						}
						array_push($arrOutput,$arrTemp);
					}
				}
			}else{
				$arrayKey = array_keys($arrXmlData);
				$arrTemp = array();
				foreach ($arrayKey as $value1){
					$key = strtoupper($value1);
					$arrTemp[$key] = $arrXmlData[$value1];
				}
				array_push($arrOutput,$arrTemp);
			}
			return $arrOutput;
		} catch (Exception $e) {
			return '';
		}
	}	
	/**
	 * Creater: Phuongtt
	 * Date: 8/11/2010
	 * Des: Ham lay danh sach id phong ban tu danh sach id can bo
	 * @param $sStaffIdList danh sach id can bo
	 * @param $arrAllStaff Mang luu thong tin can bo
	 */
	function GetUnitIdListFromStaffIdList($sStaffIdList, $arrAllStaff){
		$arrStaffId = explode(',', $sStaffIdList);
		$sUnitIdList = '';
		foreach ($arrStaffId as $sStaffId){
			foreach ($arrAllStaff As $staff)
	 			if ($sStaffId == $staff['id']){
	 				$sUnitIdList .= $staff['unit_id'].',';
	 				break;
	 			}
		}
		return substr($sUnitIdList, 0, -1);
	} 	
	/**
	 * Ham lay gia tri trong mot mang
	 * @param unknown_type $arrValue : mang gia tri
	 * @param unknown_type $sColId : Ten cot Id can so sanh
	 * @param unknown_type $sColName : Ten cot can lay gia tri
	 * @param unknown_type $svalue : Gia tri can so sanh
	 */
	public function getValueInArray($arrValue, $sColId, $sColName, $svalue){
		foreach ($arrValue as $valueSet) {
			if($valueSet[$sColId] == $svalue)
				return $valueSet[$sColName];
		}
	}
 	/*
	 * Nguoi tạo: PHUONGTT
	 * date: 27/10/2011
	 * $search : cụm từ tìm kiếm
	 * $str : chuỗi cần tô màu
	*/
 	public static function searchStringColor($search,$str){
		if(!is_null($search) & $search!='' & $search!=''){
			$search= mb_strtoupper($search,'UTF-8');
			$strUp = mb_strtoupper($str,'UTF-8');
			$srOut = '';
			$searchlen = mb_strlen($search,'UTF-8');
			mb_regex_encoding('UTF-8'); 
			$arrstr = mb_split($search, $strUp);
			$start = 0;
			$count = sizeof($arrstr);
			for ($i = 0; $i < $count; $i++){
				$length = mb_strlen($arrstr[$i],'UTF-8');
				$srOut .= mb_substr($str, $start,$length,'UTF-8'); 
				$srOut .= '<span class = "lblcolor">'.mb_substr($str, ($start + $length),$searchlen,'UTF-8').'</span>';
				$start += $length + $searchlen;
			}	
		}
		else
			return $str;
		return 	$srOut;	
	}
	/*
	 * @creater: Trinh Thanh Phuong
	 * @date: 21/11/2011
	 */
	public function DOC_GetAllDocumentFileAttach($documentId, $pFileTyle, $pTableObject){
		$objConn = new  Efy_DB_Connection(); 
		$sql = "Doc_GetAllDocumentFileAttach ";
		$sql = $sql . "'" . $documentId . "'";
		$sql = $sql . ",'" . $pFileTyle . "'";
		$sql = $sql . ",'" . $pTableObject . "'";
		try {						
			$arrResult = $objConn->adodbQueryDataInNameMode($sql);					
		}catch (Exception $e){
			echo $e->getMessage();
		};				
		return $arrResult;		
	}	
	/*
	 * @creater: Trinh Thanh Phuong
	 * @date: 21/11/2011
	 */
	public function DeleteAttachFiles($listId, $sDocType, $sTableName, $sdelimitor = '!#~$|*'){
		$objConn = new  Efy_DB_Connection();
		/*Get list Attach Files */ 
		$sql = "Exec ECS_GetFileNameInDoc ";
		$sql .= "'" . $listId . "'";
		$sql .= ",'" . $sDocType . "'";
		$sql .= ",'" . $sTableName . "'";
		$sql .= ",'" . $sdelimitor . "'";
		try {						
			$arrResult = $objConn->adodbQueryDataInNameMode($sql);					
		}catch (Exception $e){
			echo $e->getMessage();
		};			
		if($arrResult != null && $arrResult != ''){
			for($index = 0;$index < sizeof($arrResult);$index++){
				//xoa file tren o cung
				$arrFileName = explode($sdelimitor, $arrResult[$index]['C_FILE_NAME']);
				$scriptUrl = $_SERVER['SCRIPT_FILENAME'];
				$scriptFileName = explode("/", $scriptUrl);
				$k = 3;
				$sWebsitePart = Efy_Init_Config::_setWebSitePath();
				$sWebsitePart = substr($sWebsitePart,1,-1);
				$linkFile = "";
				for($i= 0;$i< sizeof($scriptFileName);$i++){
					if($scriptFileName[$i] == $sWebsitePart){
						$k = $i;
						break;
					}
				}
				for($j = 0; $j <=$k; $j++ ){
					$linkFile .= $scriptFileName[$j]."\\";
				}
				$linkFile .= "public\attach-file\\";
				for($i =0; $i < sizeof($arrFileName); $i ++){
					$fileId = explode("!~!", $arrFileName[$i]);
					$fileId = explode("_" ,$fileId[0]);
					$unlink = $linkFile . $fileId[0] . "\\" . $fileId[1] . "\\" . "\\" . $fileId[2] . "\\" . $arrFileName[$i];
					unlink($unlink);
				}
				/*Delete Attach Files */
				$sql = "Exec DeleteAttachFiles ";
				$sql .= "'" . $listId . "'";
				$sql .= ",'" . $sDocType . "'";
				$sql .= ",'" . $sTableName . "'";
				$sql .= ",'" . $sdelimitor . "'";
				try {			
					$arrTempResult = $objConn->adodbExecSqlString($sql); 
				}catch (Exception $e){
					echo $e->getMessage();
				}
			}
		}
	}
	/*
	 * @creater: Trinh Thanh Phuong
	 * @date: 21/11/2011
	 */
	public function getListByTagName($listTypeCode,$tagName,$tagValue){
		$sFilePath = Efy_Init_Config::_setXmlFileUrlPath(1) . "list/output/$listTypeCode.xml";
		$objXmlData = new Zend_Config_Xml($sFilePath,'data_list');
		$arrXmlData = $objXmlData->item->toArray();
		$arrOutput = array();
		if (isset($arrXmlData[0]) && is_array($arrXmlData[0])){
			foreach($arrXmlData as $value){
				if($value[$tagName] == $tagValue)
					array_push($arrOutput,array('C_CODE'=>$value['c_code'],'C_NAME'=>$value['c_name'],'C_STATUS'=>$value['c_status']));
			}
		}else{
			if($arrXmlData[$tagName] == $tagValue)
				array_push($arrOutput,array('C_CODE'=>$arrXmlData['c_code'],'C_NAME'=>$arrXmlData['c_name'],'C_STATUS'=>$value['c_status']));
		}
		return $arrOutput;
	}
 	/**
 	 * Trinh Thanh Phuong
 	 * Ham lay thong tin trong danh muc
 	 * @param unknown_type $listTypeCode  	- Ma loai danh muc
 	 * @param unknown_type $tagNameList   	- Danh sach ten the
 	 * @param unknown_type $tagValueList	- Danh sach gia tri 
 	 * @param unknown_type $tagInfo			- Ten the hien thi them thong tin cho cot c_name
 	 * @param unknown_type $levelXmlFile	- Tham so quy dinh duong dan duoc file XML
 	 */
	public function getListByTagNameList($listTypeCode,$tagNameList,$tagValueList,$tagInfo = '',$levelXmlFile = 1){
		$objConfig = new Efy_Init_Config();
		$sFilePath = $objConfig->_setXmlFileUrlPath($levelXmlFile) . "list/output/$listTypeCode.xml";
		$objXmlData = new Zend_Config_Xml($sFilePath,'data_list');
		$arrXmlData = $objXmlData->item->toArray();
		//var_dump($arrXmlData);
		$arrOutput = array();
		$arrTagName = explode(';', $tagNameList);
		$arrTagValue = explode(';', $tagValueList); 
		//var_dump($arrTagName);
		//var_dump($arrTagValue);
		$len = sizeof($arrTagName);
		if (isset($arrXmlData[0]) && is_array($arrXmlData[0])){
			foreach($arrXmlData as $value){
				$count = 0;
				for ($i = 0; $i < $len; $i++){
					//echo $arrTagName[$i] . '--' . $value[$arrTagName[$i]].'<br>';
					if ($value[$arrTagName[$i]] != $arrTagValue[$i]){
						$count = 1; break;
					}
				}
				if ($count == 0){
					$name = $value['c_name'];
					if ($tagInfo)
						$name .= ', ' . $value[$tagInfo];
					array_push($arrOutput,array('C_CODE'=>$value['c_code'],'C_NAME'=>$name,'C_STATUS'=>$value['c_status']));
				}	
			}
		}else{
			$count = 0;
			for ($i = 0; $i < $len; $i++){
				if ($value[$arrTagName[$i]] != $arrTagValue[$i]){
					$count = 1; break;
				}
			}
			if ($count == 0){
				$name = $value['c_name'];
				if ($tagInfo)
					$name .= ', ' . $value[$tagInfo];
				array_push($arrOutput,array('C_CODE'=>$arrXmlData['c_code'],'C_NAME'=>$tagInfo,'C_STATUS'=>$value['c_status']));
			}
		}
		return $arrOutput;
	}
 	/**
	 * Nguoi Tao: Phuongtt
	 * Ham tao mang nam tuyen sinh
	 * @param unknown_type $creatYear : nam khoi tao
	 * @param unknown_type $currentYear: Nam hien tai
	 */
	public function generateYear(){
		$arrYear = array();
		$startYear = Efy_Init_Config::_setStartYear();
		for($i = $startYear; $i <= date('Y') + 1; $i++){
			$year = array('C_CODE' => $i,'C_NAME' => $i);
			array_push($arrYear, $year);
		}
		return $arrYear;
	}
 	/**
	 * Nguoi Tao: Phuongtt
	 * Ham tao mang nam tuyen sinh
	 * @param unknown_type $creatYear : nam khoi tao
	 * @param unknown_type $currentYear: Nam hien tai
	 */
	public function generateMonth(){
		$arrMonth = array();
		for($i = 1; $i <= 12; $i++){
			$month = array('C_CODE' => $i,'C_NAME' => $i);
			array_push($arrMonth, $month);
		}
		return $arrMonth;
	}
	/**
	 * cuongnh
	 * Lay phong ban cua don vị hien tai $_SESSION['OWNER_CODE']
	 */
 	public static function ecsGetAllDepartment(){
		$k = 0;		
		$sRootId = ""; $arrDepartment = array();
		foreach($_SESSION['arr_all_unit'] as $sUnitId){	
			if (is_null($sUnitId['parent_id'])){
				$sRootId = $sUnitId['id'];
			}			
			if ($sUnitId['ownerCode'] == $_SESSION['OWNER_CODE'] && $sUnitId['parent_id'] != "" && $sRootId != $sUnitId['parent_id']){
				$arrDepartment[$k] =  $sUnitId;
				$k++;
			}
		}
		return $arrDepartment;	
	}
	/**
	 * Lay ten tinh thanh tu ma tinh
	 */
 	public function getProvinceNamebyProvinceCode($sCode){ 
		$sFilePath = Efy_Init_Config::_setXmlFileUrlPath(1) . "list/output/DM_TINH_THANH.xml";
		$objXmlData = new Zend_Config_Xml($sFilePath,'data_list');
		$arrXmlData = $objXmlData->item->toArray();
		$sName = '';
		if (is_array($arrXmlData[0])){
			foreach($arrXmlData as $value){
				if($value['c_code']==$sCode){
					$sName = $value['c_name'];
					break;
				}
			}
		}
		return $sName;
	}
	/**
	 * Phuongtt
	 * Ham cong them so 0 vao truoc chu so
	 * @param unknown_type $num
	 * @param unknown_type $nRezo
	 */
	public function addRezoNumber($num, $nRezo){
		$nRAdd  = $nRezo - strlen($num);
		$sRezo = '';
		for ($i = 0; $i < $nRAdd; $i++)
			$sRezo .= '0';
		$num = $sRezo . $num;
		return $num;
	}
	
 	/**
	 * Creater: Phuongtt
	 * Date: 29/10/2010
	 * Des: Tao form loc tieu chi tim kiem tren man hinh danh sach
	 * @param unknown_type $sStaffId Id nguoi dang nhap hien thoi
	 * @param unknown_type $arrRecordType Mang nay la ket qua cua ham eCSRecordTypeGetAllByStaff
	 * @param $sRecordTypId : Pk cua TTHC duoc chon
	 * @param unknown_type $roles Vai tro nguoi dang nhap hien thoi
	 */
	public function genEcsFilterFrom($staffId, $roles, $arrGroupRecordType,$arrRecordType, $arrInput){
		$shtml = '';
		$shtml .='<table id="table-search">
				<col width="15%"></col>
				<col width="10%"></col>
				<col width="12%"></col>
				<col width="10%"></col>
				<col width="18%"></col>
				<col width="10%"></col>
				<col width="10%"></col>
				<col width="15%"></col>';

		$shtml .='<tr>
					<td>
						<label class = "normal_label" for="groupRecordTypeFilter">Nhóm loại hồ sơ</label>
					</td>';

		$shtml .='<td colspan = "3">';

		$shtml .='<select data-placeholder=" " name ="groupRecordTypeFilter" id ="groupRecordTypeFilter" style="width:100%;" class="chzn-select" tabindex="2">';
		$shtml .= Efy_Library::_generateSelectOption($arrGroupRecordType,'C_CODE','C_CODE','C_NAME',$sGroupRecordType);

		$shtml .='</select>';

		$shtml .='</td>
					<td style = "padding-left:20px;">
						<label class = "normal_label" for = "recordTypeFilter" >Loại hồ sơ</label>
					</td>
					<td colspan = "3">';
		$shtml .='<select data-placeholder=" " name ="recordTypeFilter" id ="recordTypeFilter" style="width:100%;" class="chzn-select" tabindex="2" >';

		$shtml .= Efy_Library::_generateSelectOption($arrRecordType,'C_CODE','C_CODE','C_NAME',$arrInput['srecordType']);

		$shtml .='</select></td></tr>';
						
		$shtml .='<tr>
					<td>
						<label class = "normal_label" for = "fromDate">Ngày tiếp nhận, Từ ngày</label>
					</td>
					<td>
						<input onchange="ResetSearch()" type="text" id="fromDate" name="fromDate" optional = "true" xml_tag_in_db="fromDate" xml_data="true" column_name="fromDate" class="normal_textbox"/>
					</td>
					<td align="center" >
						<label class = "normal_label" for = "toDate" >Đến ngày</label>
					</td>
					<td>
						<input onchange="ResetSearch()" type="text" id="toDate"  name="toDate" optional = "true" xml_tag_in_db="toDate" xml_data="true" column_name="toDate" class="normal_textbox"/>
					</td>
					<td style = "padding-left:20px;">
						<label class = "normal_label" for = "fullTextSearch">Từ khóa tìm kiếm</label>
					</td>
					<td colspan = "3">
						<input onchange="ResetSearch()" type="text" id="fullTextSearch" optional = "true" name="fullTextSearch" xml_tag_in_db="fullTextSearch" xml_data="true" column_name="fullTextSearch"  class="normal_textbox" value="" />
					</td>
				</tr>
				       
			</table>';
		$shtml .= '<script type="text/javascript">
			var arrRecordType ='. json_encode($arrRecordType).';
			jQuery(".chzn-select").chosen(); 
			$( "#fromDate" ).datepicker({changeMonth: true,gotoCurrent: true,minDate: new Date(1945, 1 - 1, 1),changeYear: true});	
			$( "#toDate" ).datepicker({changeMonth: true,gotoCurrent: true,minDate: new Date(1945, 1 - 1, 1),changeYear: true});	
		</script>';
		return $shtml;
	}
	/**
	 * Creater: Truongdv
	 * Date: 21/08/2012
	 * Des: Ham sinh ma cua mot ho so
	 * @param $recordNumber So luong ho so
	 */
	 function generateRecordCode($recordNumber){
	 	$code_length = 7;
		$length = strlen($recordNumber);
		for($i = $length;$i< $code_length;$i++){
			$recordNumber = '0'.$recordNumber;
		}
		$year = substr(date("y"), 0,2);
		$v_str_ret = $_SESSION['OWNER_CODE'].".".$recordNumber.".".$year;
		return $v_str_ret;
	}

	/**
	 * Enter to mau tu khoa tim kiem..
	 *
	 * @param $nameStrColor :  Tu cantim kiem(so, ki tu,ngay thang nam)
	 * @param $nameStrInput : Chuoi tu tim thay tu Tu can tim kiem
	 * @return Xau ki tu duoc to mau o Tu can tim kiem
	 */
	public static function searchCharColor($nameStrColor,$nameStrInput){ 
		$strText =  $nameStrColor ;
		$nameStrOutput ='';
		$nameStrOutput .= str_replace(Efy_Library::Lower2Upper(trim($nameStrColor)),Efy_Library::Lower2Upper(trim($strText)),trim($nameStrInput));
		return 	$nameStrOutput;	
	}

	/**
	 * @editer: Truongdv
	 * @editor: Phuongtt 10/01/2013
	 * @listAttach: Chuoi gia tri tai lieu kem theo ho so
	 * @listAttach: Chuoi url tai lieu kem theo ho so
	 * @sDelimitor  : Ký tự phân tách giữa các phần tử
	 * @see : Di chuyển danh sách file từ thư mục tạm sang thư mục lưu trữ
	 * @return :
	 * 			$sFileNameList:	Mang danh sach ten file da duoc upload len o cung
	 * 
	 * @package : Efy_Publib_Library
	 * 			
	 **/

	public  function _uploadFileAttachList($listUrlAttach, $sDir, $sDelimitor = "!~~!"){
		$path = self::_createFolder($sDir,date('Y'),date('m'),date('d'));
		$sFileNameList = "";		
		$arrUrlAttach=explode($sDelimitor,$listUrlAttach);
		$count=sizeof($arrUrlAttach);
		if($count==0){
			return $sFileNameList;
		}
		for ($i=0; $i < $count; $i++) {
			$urlTemp = '..'.$arrUrlAttach[$i];
			$arr = explode('!~!', $urlTemp);
			$filename = end($arr);
			$random = self::_get_randon_number();
			$fodel = date("Y").'_'.date("m").'_'.date("d")."_".date("H").date("i").date("u").$random."!~!";
			$sFullFileName = $fodel. $filename;	
			$dest = $path . self::_convertVNtoEN($sFullFileName);
			//Di chuyen sang thu muc luu tru
			if(file_exists($urlTemp)){
				copy($urlTemp, $dest);
				//Xoa file o thu muc tam
				unlink($urlTemp);
			}				
			$sFileNameList .= $sFullFileName . $sDelimitor;
		}
		$sFileNameList = substr($sFileNameList,0,strlen($sFileNameList) - strlen($sDelimitor));
		// tra lai gia tri			
		return self::_convertVNtoEN($sFileNameList);			
	}

	/**
	 * Creater: KHOINV
	 *
	 * @return Ham lay mo so ngau nhien
	 */
	function _get_randon_number(){
		$ret_value = mt_rand(1,1000000);
		return $ret_value;
	}

	/**
	 * Creater: KHOINV
	 *
	 * @param $strText: chuoi ky tu can chuyen font tu VN sang EN
	 * @return tra ve chuoi khong dau
	 */
    public function _convertVNtoEN($strText){
    	
    	$vnChars = array("á","à","ả","ã","ạ","ă","ắ","ằ","ẳ","ẵ","ặ","â","ấ","ầ","ẩ","ẫ","ậ","é","è","ẻ","ẽ","ẹ","ê","ế","ề","ể","ễ","ệ","í","ì","ì","ỉ","ĩ","ị","ó","ò","ỏ","õ","ọ","ô","ố","ồ","ổ","ỗ","ộ","ơ","ớ","ờ","ở","ỡ","ợ","ú","ù","ủ","ũ","ụ","ư","ứ","ừ","ử","ữ","ự","ý","ỳ","ỷ","ỹ","ỵ","đ","Á","﻿À","Ả","Ã","Ạ","Ă","Ắ","Ằ","Ẳ","Ẵ","Ặ","Â","Ấ","Ầ","Ẩ","Ẫ","Ậ","É","È","Ẻ","Ẽ","Ẹ","Ê","Ế","Ề","Ể","Ễ","Ệ","Í","Ì","Ỉ","Ĩ","Ị","Ó","Ò","Ỏ","Õ","Ọ","Ô","Ố","Ồ","Ổ","Ỗ","Ộ","Ơ","Ớ","Ờ","Ở","Ỡ","Ợ","Ú","Ù","Ủ","Ũ","Ụ","Ư","Ứ","Ừ","Ử","Ữ","Ự","Ý","Ỳ","Ỷ","Ỹ","Ỵ","Đ");
    	$enChars = array("a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","e","e","e","e","e","e","e","e","e","e","e","i","i","i","i","i","i","o","o","o","o","o","o","o","o","o","o","o","o","o","o","o","o","o","u","u","u","u","u","u","u","u","u","u","u","y","y","y","y","y","d","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","E","E","E","E","E","E","E","E","E","E","E","I","I","I","I","I","O","O","O","O","O","O","O","O","O","O","O","O","O","O","O","O","O","U","U","U","U","U","U","U","U","U","U","U","Y","Y","Y","Y","Y","D");
    	for($i =0; $i <sizeof($vnChars); $i ++){
			$strText = str_replace($vnChars[$i], $enChars[$i], $strText);
		}	
		return 	$strText; 
    }

    public function uploadAjaxTemp($uploaddir,$valueName='uploadfile'){
    	
    	$uploaddir = '..' . $uploaddir;
		if(!file_exists($uploaddir)){
			mkdir($uploaddir);	
		}
		$time = time();
		$filename = basename($_FILES[$valueName]['name']);
		$arrTemp = explode('.', $filename);
		$ext = end($arrTemp);
		$filename = substr($filename, 0,strlen($filename)- strlen($ext));
		$filename .= strtolower($ext);
		$file = $uploaddir . $time . '!~!' . $filename; 
		$file = self::_convertVNtoEN($file);

		if(is_file($_FILES[$valueName]['name'])||$_FILES[$valueName]['name']!=''){
			if (move_uploaded_file($_FILES[$valueName]['tmp_name'], $file)) { 
			  return str_replace('..','',$file); 
			}else {
				return "error";
			}			
		}else{
			return "error";
		}		
    }
	
	public function uploadAjaxTempImage($uploaddir,$valueName='uploadfile'){
    	
    	$uploaddir = '..' . $uploaddir;
		if(!file_exists($uploaddir)){
			mkdir($uploaddir);	
		}
		$time = time();
		$filename = basename($_FILES[$valueName]['name']);
		$arrTemp = explode('.', $filename);
		$ext = end($arrTemp);
		$filename = substr($filename, 0,strlen($filename)- strlen($ext));
		$filename .= strtolower($ext);
		$file = $uploaddir . $time . '!~!' . $filename; 
		$file = self::_convertVNtoEN($file);

		if(is_file($_FILES[$valueName]['name'])||$_FILES[$valueName]['name']!=''){
			if (move_uploaded_file($_FILES[$valueName]['tmp_name'], $file)) {
				Zend_Loader::loadClass('Efy_Function_SimpleImage');
			   $image = new Efy_Function_SimpleImage();
			   $image->load($file);
			   // ->resize(150,100)
			   // ->save($file,258,195);
			   $image->resizeToHeight(100);
			   $image->resizeToWidth(150);
			   $image->save($file);


			  return str_replace('..','',$file); 
			}else {
				return "error";
			}			
		}else{
			return "error";
		}		
    }
    

     /**
	 * @author : KHOINV
	 * @since : 19/05/2011
	 * @see : Lay thong tin file dinh kem
	 * @param :
	 * 			$sRecordID: ma ho so
	 * 			$sKeyAttach:ma tai lieu kem theo
	 * @return : 
	 * 			$arrResult: mang 2 chieu chua thong tin file dinh kem
	 * 			
	 * */
	public function QLHTFileGetSingle($sRecordID,$sKeyAttach){	
		$objConn = new  Efy_DB_Connection(); 		
		$sql = "Exec EfyLib_libFileGetSingle  ";
		$sql .= "'" . $sRecordID . "'";
		$sql .= ",'" . $sKeyAttach . "'";
		// echo $sql ; exit();
		// thuc hien cap nhat du lieu vao csdl
		try {			
			$arrResult = $objConn->adodbQueryDataInNameMode($sql) ; 			
			
		}catch (Exception $e){
			echo $e->getMessage();
		};				
		return $arrResult;	
		//var_dump($arrResult) . 'du lieu ket xuat tu database';
	}
	
	/**
	 * Creater: KHOINV
	 * Date: 19/05/2011
	 * Discription: Tao folder
	 *
	 * @param $path: noi can tao folder
	 * @param $folderYear: tao ra folder nam
	 * @param $folderMonth: tao ra folder thang
	 * @return tra ve duong dan toi folder
	 */
	public function _createFolder($pathLink, $folderYear, $folderMonth, $sCurrentDay = ""){
		$sPath = '..' . str_replace("/","\\",$pathLink);
		//echo $sPath.$folderYear; //exit;
		if(!file_exists($sPath . $folderYear)){
			mkdir($sPath . $folderYear, 0777);	      
        	$sPath = $sPath . $folderYear;
            if(!file_exists($sPath . chr(92) . $folderMonth)){
        		mkdir($sPath . chr(92) . $folderMonth, 0777);
            }
		}else {
			//$sPath = '..' . $sPath . $folderYear;
			$sPath =  $sPath . $folderYear;
            if(!file_exists($sPath . chr(92) . $folderMonth)){
        		mkdir($sPath . chr(92) . $folderMonth, 0777);
        	}
		}
		//Tao ngay trong nam->thang
		if(!file_exists($sPath . chr(92) . $folderMonth . chr(92) . $sCurrentDay)){
			mkdir($sPath . chr(92) . $folderMonth . chr(92) . $sCurrentDay, 0777);
		}
		//
		$strReturn = '..' . $pathLink . $folderYear . '/' . $folderMonth . '/' . $sCurrentDay.'/';
		return $strReturn;
	}

     public function getUrlAttachFileThumb($arrFileList){
         //Tao doi tuong thong tin config
         $objConfig = new Efy_Init_Config();
         if($arrFileList !=''){
             foreach ($arrFileList as $key => $value) {
                 $arrFilename = explode('!~!',$value);
                 $file_id   = explode("_", $arrFilename[0]);
                 //Get URL
                 $sActionUrl = $objConfig->_setAttachFileUrlPath() . $file_id[0] . "/" . $file_id[1] . "/" . $file_id[2] . "/" . $value;
             }
         }
         return $sActionUrl;
     }


	public function FormAttachFile($arrFileList,$type,$fk_doc='',$fileName ='FileName',$readonly = false){				
		//Tao doi tuong thong tin config
		$objConfig = new Efy_Init_Config();
		$strHTML ='<div>';		
		$strHTML .= '<label class="normal_label" style="width:25%;padding-left: 0.5%; float:left">File đính kèm</label>';
		$strHTML .= '<div style="width:72%;margin-left:25%;">';
		$strHTML .= '<div id="listAttach" style="margin-left:6px;">';
		if($arrFileList !=''){
			foreach ($arrFileList as $key => $value) {				
				$arrFilename = explode('!~!',$value);					
				$file_name = $arrFilename[1];
				$file_id   = explode("_", $arrFilename[0]);									
				$fileExtensiona = explode('.', $file_name);
				$fileExtension = end($fileExtensiona);
				//Get URL
				$sActionUrl = $objConfig->_setAttachFileUrlPath() . $file_id[0] . "/" . $file_id[1] . "/" . $file_id[2] . "/" . $value;
				$strHTML .= '<div class="success">';
				$strHTML .= '<input id="chk_attach" type="checkbox" value="'.$sActionUrl.'" checked="checked">';
				$strHTML .= '<a class = "attach-file '.$fileExtension.'" alt="" href="'. $sActionUrl .'">'. $file_name .'</a>';
				$strHTML .= '</div>';
			}
		}
		$strHTML .= '</div>';
		if(!$readonly){
			$strHTML .= '<div id="files" ></div><div><span id="upload" class="el clattachfile">Thêm file </span>|<span class="el delfiles"> Xóa files</span></div>';
		}
		$strHTML .= '</div></div>';
		if(!$readonly){
			$strHTML .= '<script>
				//Attach file
				var btnUpload = $(".clattachfile");
				var status = $("#status");
				attachFile(btnUpload,status,urlPath);
				//Click Xóa files
				$(".delfiles").click(function(){
					delfiles($(this),urlPath,"'.$type.'","'.$fk_doc.'");
				});
			</script>';
		}
		return $strHTML;
	}

	public function FormAttachDocument($fileuploaded,$type,$fk_doc='',$fileName ='FileName',$readonly = false){				
		//Tao doi tuong thong tin config
		$objConfig = new Efy_Init_Config();
		$strHTML .= '<label class="normal_label" style="width:25%;padding-left: 0.5%; float:left">File đính kèm</label>';
		$strHTML .= '<div style="width:72%;display:inline-block; float:left;margin-left:0;">';
		if(!$readonly){
			$strHTML .= '<input type="button" id="clattachfile" value="Chọn file tài liệu" class="btnupload"/>';
		}
		$strHTML .= '<div id="listAttach" style="margin-left:6px; display:inline-block">';
		if($fileuploaded !=''){
			$arrFilename = explode('!~!',$fileuploaded);					
			$file_name = $arrFilename[1];
			$file_id   = explode("_", $arrFilename[0]);									
			$fileExtensiona = explode('.', $file_name);
			$fileExtension = end($fileExtensiona);
			//Get URL
			$sActionUrl = $objConfig->_setAttachFileUrlPath() . $file_id[0] . "/" . $file_id[1] . "/" . $file_id[2] . "/" . $fileuploaded;
			$strHTML .= '<input style="display:none;" id="chk_attach" type="checkbox" value="'.$sActionUrl.'" checked="checked" style="display:inline-block">';
			$strHTML .= '<a target="_blank" style="display:inline-block" class = "attach-file '.$fileExtension.'" alt="" href="'. $sActionUrl .'">'. $file_name .'</a>';
			
		}
		$strHTML .= '</div></div>';
		if(!$readonly){
			$strHTML .= '<script>
				//Attach file
				var btnUpload = $("#clattachfile");
				var status = $("#status");
				attachFile(btnUpload,status,urlPath);
			</script>';
		}
		return $strHTML;
	}

	public function FormAttachFlash($fileuploaded,$type,$fk_doc='',$fileName ='FileName',$readonly = false){				
		//Tao doi tuong thong tin config
		$objConfig = new Efy_Init_Config();
		$strHTML .= '<label class="normal_label" style="width:25%;padding-left: 0.5%; float:left">File view flash</label>';
		$strHTML .= '<div style="width:72%;display:inline-block; float:left;margin-left:0;">';
		if(!$readonly){
			$strHTML .= '<input type="button" id="uploadflash" value="Chọn file flash" class="btnupload"/>';
		}
		$strHTML .= '<div id="fileflash" style="margin-left:6px; display:inline-block">';
		if($fileuploaded !=''){
			$arrFilename = explode('!~!',$fileuploaded);					
			$file_name = $arrFilename[1];
			$file_id   = explode("_", $arrFilename[0]);									
			$fileExtensiona = explode('.', $file_name);
			$fileExtension = end($fileExtensiona);
			//Get URL
			$sActionUrl = $objConfig->_setAttachFileUrlPath() . $file_id[0] . "/" . $file_id[1] . "/" . $file_id[2] . "/" . $fileuploaded;
			$strHTML .= '<input id="chk_attach_flash" style="display:none" type="checkbox" value="'.$sActionUrl.'" checked="checked" style="display:inline-block">';
			$strHTML .= '<a target="_blank" style="display:inline-block" class = "attach-file '.$fileExtension.'" alt="" href="'. $sActionUrl .'">'. $file_name .'</a>';
			
		}
		$strHTML .= '</div></div>';
		if(!$readonly){
			$strHTML .= '<script>
				//Attach file
				var btnUpload = $("#uploadflash");
				var status = $("#status");
				attachFileFlash(btnUpload,status,urlPath);
			</script>';
		}
		return $strHTML;
	}

     public function FormAttachFileThumbnail($srcThumBnail,$type,$fk_doc='',$fileName ='FileName',$readonly = false){
         //Tao doi tuong thong tin config
         $objConfig = new Efy_Init_Config();
         $strHTML = '';
         if(!$readonly){
            	$strHTML .= '<div style=""><span id="uploadThumbnail" class="el clattachfileThumbnail addicon" title"Sửa ảnh đại diện"></span></div>';
             $strHTML .= '<div id="listAttachThumbnail" style="float: none; margin-left: 25%;">';
             if($srcThumBnail !=''){
                     $sActionUrl = $srcThumBnail;
                     $strHTML .= '<div class="successThumbnail">';
                     $strHTML .= '<input id="chk_attach_thumb" style="display:none;" type="checkbox" value="'.$sActionUrl.'" checked="checked">';
                     $strHTML .= '<img class="" src="'.$sActionUrl.'">';
                     $strHTML .= '</div>';
                 
             }else{
             	$strHTML .= '<div class="successThumbnail">';
             	$sActionUrl = $objConfig->_setAttachFileUrlPath().'default/default.jpg';
	            $strHTML .= '<img class="" src="'.$sActionUrl.'">';
	            $strHTML .= '</div>';
             }
             $strHTML .= '</div>';
         }
        
         $strHTML .= '<div style="clear:both;"></div>';
         if(!$readonly){
             $strHTML .= '<script>
				//Attach file
				var btnUpload = $(".clattachfileThumbnail");
				var status = $("#status");
				attachFileThumbnail(btnUpload,status,urlPath);
				//Click Xóa files
				$(".delfilesThumbnail").click(function(){
					delfilesThumbnail($(this),urlPath,"'.$type.'","'.$fk_doc.'");
				});
			</script>';
         }
         return $strHTML;
     }

	/**
	 * Nguoi tao tuanpm
	 * Đính kèm file khi cai chinh ho so
	 *
	 */
	public function FormAttachFileChangeRecord($arrFileList,$fileName ='FileName',$readonly = false,$doctype='HO_SO_CAI_CHINH',$fk_doc =''){
		//Tao doi tuong thong tin config
		$objConfig = new Efy_Init_Config();
		$strHTML ='<div>';		
		$strHTML .= '<label class="normal_label" style="width:20%; float:left">File đính kèm</label>';
		$strHTML .= '<div style="width:72%;margin-left:19.9%;">';
		$strHTML .= '<div id="listAttach" style="margin-left:6px;">';
		if($arrFileList !=''){
			foreach ($arrFileList as $key => $value) {
				$file = $value['C_FILE_NAME'];
				$arrFilename = explode('!~!',$file);					
				$file_name = $arrFilename[1];
				$file_id   = explode("_", $arrFilename[0]);									
				//Get URL
				$sActionUrl = $objConfig->_setAttachFileUrlPath() . $file_id[0] . "/" . $file_id[1] . "/" . $file_id[2] . "/" . $file;
				$strHTML .= '<div class="success">';
				$strHTML .= '<input id="chk_attach" type="checkbox" value="'.$sActionUrl.'" checked="checked">';
				$strHTML .= '<a alt="" href="'. $sActionUrl .'">'. $file_name .'</a>';
				$strHTML .= '</div>';
			}
		}
		$strHTML .= '</div>';
		if(!$readonly){

			$strHTML .= '<div id="files" ></div><div><span id="upload" class="el clattachfile">Thêm file </span>|<span class="el delfilesrecord"> Xóa files</span></div>';
		}
		$strHTML .= '</div></div>';
		if(!$readonly){

			$strHTML .= '<script>
				//Attach file
				var btnUpload = $(".clattachfile");
				var status = $("#status");
				attachFile(btnUpload,status,urlPath);
				//Click Xóa files
				$(".delfilesrecord").click(function(){
					delfilesrecord($(this),urlPath,"'.$doctype.'","'.$fk_doc.'");
				});
			</script>';
		}
		return $strHTML;
	}

	function QLDTLoadFile ($sPath, $sFileName){
		$this->_file = $sPath . $sFileName;
		$this->_file = file_get_contents($this->_file,FILE_BINARY);
		return $this->_file;	
	}

	/**
	 * Nguoi tao HAIDV
	 * Ngay tao 19-09-2011
	 * Y Nghia lay danh sach tai lieu kem theo
	 */
	 public function getAllListObjectCode($sOwnerCode,$sCode, $optCache = ""){
		// Tao doi tuong xu ly du lieu
		$objConn = new  Efy_DB_Connection(); 
		$sql = "EfyLib_GetAllName_TLKT ";
		$sql = $sql . " '" . $sOwnerCode . "'";
		$sql = $sql . " ,'" . $sCode . "'";
		//echo $sql . '<br>';exit;
		try {
			$arrObject = $objConn->adodbQueryDataInNameMode($sql,$optCache);
		}catch (Exception $e){
			echo $e->getMessage();
		}
		return $arrObject;
	}	
	/**
	* Nguoi tao: KHOINV
	* Ngay tao: 22/04/2011
	* Y nghia:Lay danh sach ten tai lieu kem theo tu danh sach ma truyen vao
	* $sOwnerCode: Ma don vi
	* $sCode: Ma danh muc
	* $sList: danh sach ma tai lieu kt	
	*/
	public function getNameFromCode($sOwnerCode,$sCode, $sList){
		// Tao doi tuong xu ly du lieu
		$objConn = new  Efy_DB_Connection(); 
		$sql = "EfyLib_NameFromCode ";
		$sql = $sql . " '" . $sOwnerCode . "'";
		$sql = $sql . " ,'" . $sCode . "'";
		$sql = $sql . " ,'" . $sList . "'";
		//echo $sql . '<br>';exit;
		try {
			$arrObject = $objConn->adodbQueryDataInNameMode($sql);
		}catch (Exception $e){
			echo $e->getMessage();
		}
		return $arrObject;
	}

	public function getNameByCode($array,$sCode){
		foreach ($array as $key => $value) {
			if($value[0] ==$sCode){
				return $value[1];
			}
		}
		return '';
	}
	/*
	Nguoi tao: Truongdv
	Chuc nang: Doc template docx xuat ra file doc
	Params: array()
	*/
	public function qlht_printDoc($arrParameter){	

		//Lay params
		$sPathXmlFile = $arrParameter['sPathXmlFile'];
		$sParrentTagName = $arrParameter['sParrentTagName'];
		$TagName = $arrParameter['TagName'];
		$sPathTemplateFile = $arrParameter['sPathTemplateFile'];
		if(isset($arrParameter['sXmlData'])){
			$sXmlData = $arrParameter['sXmlData'];
		}else{
			$sXmlData = '';
		}
		$arrRecord = array();
		$arrRecord = $arrParameter['arrRecord'];
		$sPathTemplateFile = $arrParameter['sPathTemplateFile'];
		$sTemplateFile = $arrParameter['sTemplateFile'];
		$sStaffName = $arrParameter['sStaffName'];
		$sPresident = $arrParameter['sPresident'];
		$sOwnerCode = $arrParameter['sOwnerCode'];
		//Goi class xu ly
		Zend_Loader::loadClass('Zend_Config_Xml');
		Zend_Loader::loadClass('Efy_phpDocx');	
		//Tao doi tuong
		$ojbConfigXml = new Zend_Config_Xml($sPathXmlFile,$sParrentTagName);
		$objXml = new Efy_Xml();
		$objQLDTFun = new Efy_Function_RecordFunctions();
		$objLib = new Efy_Library();
		
		$dirTemplate = $sPathTemplateFile.$sTemplateFile;
		$phpdocx = new Efy_phpDocx($dirTemplate);

		$phpdocx->assignToHeader("#HEADER1#","Header 1"); // basic field mapping to header
		$phpdocx->assignToFooter("#FOOTER1#","Footer 1"); // basic field mapping to footer
		$sXmlData = '<?xml version="1.0" encoding="UTF-8"?>'.$sXmlData;
		//
		if(isset($ojbConfigXml->$TagName)){
		    $TagElements = $ojbConfigXml->$TagName->toArray();								//Chuyen doi cac phan tu trong .xml cua the $TagName ra mang		    
		    if(is_array($TagElements)){	
		    	//Duyet cac phan tu cua														
		        foreach ($TagElements as $elements => $arrElement){
		           	       
		            //Bien xac dinh co phai lay du lieu tu xau XML luu trong DB khong?
		            $sFromXmlData 		= $arrElement["from_xml_data"];
		            //Dinh dang kieu du lieu
					$sDataFormat 		= $arrElement["data_format"];					
					//Tim xau can thay the
					$sFindString 		= $arrElement["find_string"];
					//Ten cot luu thong tin lay du lieu thay the
					$sFieldName 		= $arrElement["field_name"];
					//Ten the luu du lieu trong xau XML thay the file temp
					$sXmlTagInDb 		= $arrElement["xml_tag_in_db"];
					//Select sql
					if(isset($arrElement["selectbox_option_sql"])){
						$selectbox_option_sql 		= $arrElement["selectbox_option_sql"];
					}else{
						$selectbox_option_sql ='';
					}
					//echo $sXmlTagInDb;exit;
					//--------------Bat dau thay the du lieu---------------------------------					
					if ($sFromXmlData == 'true' && $sXmlData != ''){				
						$sValue = trim($objXml->_xmlGetXmlTagValue($sXmlData,"data_list",$sXmlTagInDb));					
					}else{//Lay du lieu tu cot						
						$sValue = trim($arrRecord[$sFieldName]);
					}

					//
					if ($sDataFormat == "breakline"){
						$sValue = $objLib->_breakLine($sValue);
					}		

					if ($sDataFormat == "isdateword" && $sValue !=''){
						$arr = explode('/', $sValue);
						$sValue = 'ngày '.$arr['0'].' tháng '.$arr['1'].' năm '.$arr['2'];
					}		
			
		       		if ($sDataFormat == "isrecordnumber"){
						$sValue = str_replace(".","/",$sValue);
			       		if(($sValue<>"")){
							$arr_string_number = split("/",$sValue);
								$sValue = $arr_string_number[3].'/'.$arr_string_number[2];
							}
						}
					//Kieu date
					if ($sFromXmlData != 'true'&& $sDataFormat == 'isdate'){
						$sValue = $objLib->_yyyymmddToDDmmyyyy($sValue);
					}
					//Kieu selectbox
					if ($sFromXmlData == 'true' && $sDataFormat == 'selectbox'){
						$selectbox_option_sql = str_replace("#OWNER_CODE#", $sOwnerCode, $selectbox_option_sql);
						$sValue = $this->getNameByCode(Efy_DB_Connection::adodbQueryDataInNumberMode($selectbox_option_sql,''),$sValue);	
					}
					
					//Kieu In giay phep dang ngay dd thang mm nam yyyy
					if ($sFromXmlData == 'true'&& $sDataFormat == 'isdatelicense'){
						if($sValue<>''){
							$sValue = $objLib->_ddmmyyyyToYYyymmdd($sValue);					
							$sValue = "ng&#224;y ".date("d", strtotime($sValue))." th&#225;ng ".date("m", strtotime($sValue))." n&#259;m ".date("Y", strtotime($sValue));
						}else{
							$sValue = "ng&#224;y...th&#225;ng...n&#259;m";
						}
					}	
											
					// Haidv Bo sung hien thi dang bang phan tai lieu kem theo			
					if($sXmlTagInDb == 'tai_lieu_kt'){
						$sVal = '';		
							if($sValue != ''){
								$arrList=$objQLDTFun->getNameFromCode($sOwnerCode,"DM_TLKT_".$arrRecord['C_RECORD_TYPE_CODE'],$sValue);
								//echo $arrList; exit;
								for($i = 0; $i < sizeof($arrList); $i ++)							
									$sVal .= '- '.$arrList[$i]['C_NAME'].'<br>';
							$sValue = $sVal;
							//Lay tai lieu khac
							$listDocAnother = $objLib->_breakLine(trim($objXml->_xmlGetXmlTagValue($sXmlData,"data_list",'tl_khac')));
							if($listDocAnother!=''){
								$arrDocAnother = explode (',',$listDocAnother);
								if (sizeof($arrDocAnother)>0){
									for($i = 0; $i < sizeof($arrDocAnother); $i ++)								
										$sValue .= '- '.$arrDocAnother[$i].'<br>';
								}
							}
						}						
					}

					if($sXmlTagInDb == 'record_form'){											
						$sNameValue = $this->getAllListObjectCode($sOwnerCode,$sValue);		
						$phpdocx->assign("#RECORD_FORM#",$sNameValue[0]['C_NAME']);
					}
					//Thay the ten don vi su dung
					$phpdocx->assign("#unitReport#",Efy_Init_Config::_setOnerReportName());
					$phpdocx->assign("#UNIT_NAME#",Efy_Init_Config::_setOnerName_Lower());
					$arrUnitReceipt = Efy_Init_Config::_setHeaderReceipt();					
					for($i = 0;$i<sizeof($arrUnitReceipt);$i++){
						if($arrUnitReceipt[$i]['OWNER_CODE'] == $_SESSION['OWNER_CODE']){
							$phpdocx->assign("#parentUnit#",$arrUnitReceipt[$i]['NAME_CERTIFICATION_0103']);
							$phpdocx->assign("#donvi#",$arrUnitReceipt[$i]['NAME_RECEIPT']);
							$phpdocx->assign("#dvchungnhan#",$arrUnitReceipt[$i]['NAME_CERTIFICATION']);
							break;
						}
					}
					// $phpdocx->assign("#tracuu#",Efy_Init_Config::_setLabelSearch());
					$sStaffName = Efy_Publib_Library::_getItemAttrById($_SESSION['arr_all_staff'],$_SESSION['staff_id'],'name');
                   // echo $sStaffName; //exit;
					//Nam luu tru
					if($arrRecord['C_TO_YEAR_SAVE'] == $arrRecord['C_FROM_YEAR_SAVE']){
						$nam_luu = $arrRecord['C_TO_YEAR_SAVE'];
					}else{
						$nam_luu = $arrRecord['C_TO_YEAR_SAVE'].'-'.$arrRecord['C_FROM_YEAR_SAVE'];
					}

					$provinces = Efy_Init_Config::_setprovinces();
					$ownerName = Efy_Init_Config::_setOnerReportName();
					
					//Thay the gia tri
					$phpdocx->assign("#nam_luu#",$nam_luu);
					$phpdocx->assign("#STAFF#",$sStaffName);
					$phpdocx->assign("#ngay#",date('d'));
					$phpdocx->assign("#thang#",date('m'));
					$phpdocx->assign("#nam#",date('Y'));
					$phpdocx->assign($sFindString,$sValue);
					$phpdocx->assign("#nguoi_thuc_hien#",$sStaffName);
					$phpdocx->assign("#chuc_vu_chu#",$sPresident);
					$phpdocx->assign("#provinces#",$provinces);
					$phpdocx->assign("#OWNER_CODE#",$ownerName);
		        }
		        
		    }
		}
		$arr = explode('.', $sTemplateFile);
		$sFileExport = 	$arr[0];
		$v_export_filename = $sFileExport.'_'.date('dmy').date('His').'.doc';
		$dir_export_file = 'public/export/' . $v_export_filename;
		$phpdocx->save($dir_export_file);
		return $v_export_filename;
	}
	/**
	*@Author: HUNGVM
	*@Since:18/11/2012
	*@Todo: Phương thức xử lý lấy danh sách TTHC theo Quyền NSD đăng nhập hiện thời
	*@para 	
	*	+ $staffId: Id cán bộ hiện thời
	*	+ $sOptionGetValue: Tùy chọn lấy dữ liệu (1: lấy danh sách TTHC mà NSD hiện thời có quyền; 2:)
	*/
	public static function getRecordTypeByCurrentStaff($sOptionGetValue = "1",$sOwnerCode = "",$staffId = ""){		
		//Tồn tại giá trị của mảng lưu thông tin loại hồ sơ TTHC thì thực hiện
		$arrRecordTypeTemp = array();
		if ($staffId == ""){
			$staffId = $_SESSION['staff_id'];
		}	
		//							
		switch($sOptionGetValue) {
				//Lấy danh sách TTHC mà NSD hiện thời có quyền Tiếp nhận & Thụ lý	
			case "1";					
				if (!isset($_SESSION['arrRecordType'])){
					$arrRecordType = Efy_Function_RecordFunctions::getAllObjectbyListCodeFull($sOwnerCode,'DM_LOAI_HO_SO');	
					foreach ($arrRecordType as $key => $value) {
						$arrReceive = explode("!@@!", $value['C_RECEIVE_LIST']);
						$arrHandle = explode("!@@!", $value['C_HANDLE_LIST']);							
						if(Efy_Library::_listHaveElement($arrReceive['0'],$staffId,',') || Efy_Library::_listHaveElement($arrHandle['0'],$staffId,',')){
							$arrRecordTypeTemp[] = $arrRecordType[$key];
						}				
					}
					return $_SESSION['arrRecordType'] = $arrRecordTypeTemp;	
				}else{
					return $_SESSION['arrRecordType'];
				}		
				break;

				//Lấy danh sách nhóm TTHC theo vai trò NSD đăng nhập hiện thời	
			case "2";					
				if (!isset($_SESSION['arrGroupRecordType'])){
					$arrGroupRecordTypeTemp = array(); $iInc = 0;
					$arrGroupRecordType = Efy_Function_RecordFunctions::getAllObjectbyListCode($sOwnerCode,'DM_NHOM_LOAI_HO_SO');
					$arrRecordType = $_SESSION['arrRecordType'];
					//Loai ho so
					$sGroupRecordTypeTemp = "";
					foreach ($_SESSION['arrRecordType'] as $key => $value) {
						$sGroupRecordTypeTemp .= $value['C_GROUP_RECORDTYPE'].",";
					}
					//Duyệt nhóm loại theo loại hồ sơ
					for ($index = 0;$index < sizeof($arrGroupRecordType);$index++){
						if (Efy_Library::_listHaveElement($sGroupRecordTypeTemp,$arrGroupRecordType[$index]['C_CODE'],',')){
							$arrGroupRecordTypeTemp[$iInc]['C_CODE'] = $arrGroupRecordType[$index]['C_CODE'];
							$arrGroupRecordTypeTemp[$iInc]['C_NAME'] = $arrGroupRecordType[$index]['C_NAME'];
							$iInc++;
						}							
					}						
					return $_SESSION['arrGroupRecordType'] = $arrGroupRecordTypeTemp;
				}else{
					return $_SESSION['arrGroupRecordType'];
				}
				break;	
			default://Mặc định lấy danh sách TTHC					
				if (!isset($_SESSION['arrRecordType'])){
					$arrRecordType = Efy_Function_RecordFunctions::getAllObjectbyListCodeFull($sOwnerCode,'DM_LOAI_HO_SO');	
					foreach ($arrRecordType as $key => $value) {
						$arrReceive = explode("!@@!", $value['C_RECEIVE_LIST']);
						$arrHandle = explode("!@@!", $value['C_HANDLE_LIST']);							
						if(Efy_Library::_listHaveElement($arrReceive['0'],$staffId,',') || Efy_Library::_listHaveElement($arrHandle['0'],$staffId,',')){
							$arrRecordTypeTemp[] = $arrRecordType[$key];
						}				
					}
					return $_SESSION['arrRecordType'] = $arrRecordTypeTemp;	
				}else{
					return $_SESSION['arrRecordType'];
				}		
		}					
	}
	/**
	 * Creater :TRUONGDV
	 * Date : 09/11/2012
	 * Idea : Return mảng lưu Tag=>value của tiêu thức lọc
	 */ 
	function getDataFilter($arrFilter, $arrFilterValue){
		$arrTagFilter = array();//Luu Tag=>value cua tieu thuc loc
		if(!isset($arrFilter[0])){
			$arrTemp = array();
			array_push($arrTemp,$arrFilter);
			$arrFilter = $arrTemp;
		}	

		foreach ($arrFilter as $key => $value) {
			$arrTemF = explode(',', $value['tag_list']);
			foreach ($arrTemF as $keyF => $valueF) {
				$arrFil = array('C_KEY'=>$valueF,'C_VALUE'=>$arrFilterValue[$valueF]);
				array_push($arrTagFilter, $arrFil);
			}
		}
		return $arrTagFilter;
	}
	/**
	 * Creater :TRUONGDV
	 * Date : 09/11/2012
	 * Idea : Replace filter trong chuoi sql
	 */ 
	function getAllData($sql, $arrTagFilter, $option = '0'){
		$arrResult = array();
		$db = new Efy_DB_Connection();
		if(is_array($arrTagFilter)){
			foreach ($arrTagFilter as $key => $value) {
				$sql = str_replace('#'.$value['C_KEY'].'#',$value['C_VALUE'] ,$sql);
			}
			//echo $sql; die();
			if($option == '1'){
				$arrResult = $db->adodbExecSqlString($sql);	
			}else{
				$arrResult = $db->adodbQueryDataInNameMode($sql);
			}
			//var_dump($arrResult); die();
		}
		return $arrResult;
	}
	/**
	 * Creater :TRUONGDV
	 * Date : 09/11/2012
	 * Idea : Doc template EXCEL và xuất ra file EXCEL
	 */ 
	public function createreportexcel($arrParameter){
		//Lay params
		$sPathXmlFile = $arrParameter['sPathXmlFile'];
		$sParrentTagName = $arrParameter['sParrentTagName'];
		$TagName = $arrParameter['TagName'];
		//Goi class xu ly
		Zend_Loader::loadClass('Zend_Config_Xml');
		Zend_Loader::loadClass('Efy_IOFactory');
		//Zend_Loader::loadClass('PHPExcel_Writer_PDF');
		//Tao doi tuong
		$ojbConfigXml = new Zend_Config_Xml($sPathXmlFile);
		$objReader = Efy_IOFactory::createReader('Excel5');
		$objPHPExcel = $objReader->load($arrParameter['sPathTemplateFile'].$arrParameter['sTemplateFile'].'.xls');
		$objPHPExcel->setActiveSheetIndex(0);
		$objWorksheet = $objPHPExcel->getActiveSheet();	
		//Lay tieu chi tim kiem
		$arrFilter = $ojbConfigXml->table_struct_of_filter_form->filter_row->toArray();
		$arrFilterValue = $arrParameter['arrFilterValue'];
		$arrTagFilter = $this->getDataFilter($arrFilter,$arrFilterValue);
		//Lay chuoi sql và replace
		$sql = $ojbConfigXml->report_sql->sql;
		$data = $this->getAllData($sql,$arrTagFilter);
		//Header
		$arrHeader = $ojbConfigXml->report_header->col->toArray();
		if(is_array($arrHeader)){
			foreach ($arrHeader as $key => $arrElement) {
				$field_name 	= $arrElement['field_name'];
				$row 			= $arrElement['row'];
				$field_column 	= $arrElement['field_column'];
				$replace 		= $arrElement['replace'];
				$type 			= $arrElement['type'];
				switch ($type) {
					case 'function':
						$params = $arrElement['param'];
						$arrParams = explode(',', $params);
						$phpFunction = $arrElement['phpFunction'];
						$pClassname = $arrElement['classname'];
						$i =0;
						$arrParamFunc = array();
						foreach ($arrParams as $key => $param) {
							if(isset($arrFilterValue[$param])){
								$arrParamFunc[] = $arrFilterValue[$param];
							}else {
								$arrParamFunc[] = $param;
							}
							$i++;
								//$params = str_replace($param,$arrFilterValue[$param], $params);
						}
						$objClass = new $pClassname;
						//echo $params; die();
						$value = $objClass->$phpFunction($arrParamFunc);
						//echo $value; die();
						//$value = call_user_func($phpFunction,$arrParams);
						break;
					
					default:
						$value = $arrFilterValue[$replace];
						break;
				}
				$rowvalue = 	$objWorksheet->getCell($field_name.$row)->getValue();
				$rowvalue = str_replace('#'.$field_column.'#', $value, $rowvalue);
				//echo $rowvalue; die();
				$objWorksheet->setCellValue($field_name.$row,$rowvalue);
			}
		}
		$level1groupid = $ojbConfigXml->report_sql->level1groupid;
		$level1groupname = $ojbConfigXml->report_sql->level1groupname;
		$merge_col_from = $ojbConfigXml->report_sql->merge_col_from;
		$merge_col_to = $ojbConfigXml->report_sql->merge_col_to;
		$baseRow = $ojbConfigXml->report_body->baseRow;
		if(isset($ojbConfigXml->report_body)){
			$TagElements = $ojbConfigXml->report_body->col_list->col->toArray();
			isset($data[0]['TOTAL_GROUP'])? $total_group = $data[0]['TOTAL_GROUP'] : $total_group = 0;
			
			$objWorksheet->insertNewRowBefore($baseRow,sizeof($data) + $total_group);
			$total = $baseRow + sizeof($data);
			if(is_array($data)){
				$count = 0;
				$default = '';
				$defaultName = '';
				$row = $baseRow;
				foreach($data as $r => $dataRow) {
					//$row = $baseRow + $r;
					if($level1groupid !=''){
						if($dataRow[$level1groupid] != $default){
							$count = 0;
							$default = $dataRow[$level1groupid];
							$defaultName = $dataRow[$level1groupname];
							$objWorksheet->mergeCells($merge_col_from.$row.':'.$merge_col_to.$row);
							$objWorksheet->setCellValue($merge_col_from.$row,$defaultName);
							$objWorksheet->getRowDimension($row)->setRowHeight(-1);
							$objWorksheet->getStyle($merge_col_from.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
							$row ++;
						}
					}
					$count ++;
					//Duyet cac phan tu cua
			        foreach ($TagElements as $elements => $arrElement){
			           	$field_name 	= $arrElement['field_name'];
			           	$field_column 	= $arrElement['field_column'];
			           	$data_format	= $arrElement['data_format'];
			           	if($data_format =='identity'){
			           		$objWorksheet->setCellValue($field_name.$row, $count);
			           	}else{
			           		$objWorksheet->setCellValue($field_name.$row, $dataRow[$field_column]);
			           	}
			        }
					//Autofit
					$objWorksheet->getRowDimension($row)->setRowHeight(-1);
					$row++;
				}
		        
		    }
		}
		$objWorksheet->removeRow($baseRow-1,1);
		/*$objWorksheet->setCellValue('G'.($row+3),'Hà Nội, ngày '.date('d').' tháng '.date('m').' năm '.date('Y'));		
		$objWorksheet->setCellValue('B'.($row+8),Efy_Publib_Library::_getItemAttrById($_SESSION['arr_all_staff'],$_SESSION['staff_id'],'name'));		*/

		/*$objPageSetup = new PHPExcel_Worksheet_PageSetup();
	    $objPageSetup->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
	    $objPageSetup->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);*/
	    //$objPageSetup->setPrintArea("E5:H7");
	    // $objPageSetup->setFitToWidth(1);
	    // $objPHPExcel->getActiveSheet()->setPageSetup($objPageSetup);
	    
		$fileName = "nv01".date('dmy').date('His');
		if($arrParameter['type'] =='excel'){
			//Xuat file
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			$fileName = $fileName.".xls";
		}else{
			//$objWriter = new PHPExcel_Writer_PDF($objPHPExcel);
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
			$objWriter->setPreCalculateFormulas(false);
			$fileName = $fileName.".pdf";
		}
		// Duong dan file report
		$path = $_SERVER['SCRIPT_FILENAME'];
		$path = substr($path, 0, -9);
		$reportFile = str_replace("/", "\\", $path) . "public\\export\\" . $fileName;
		$objWriter->save($reportFile);
		return $fileName;
	}
	/**
	 * Creater :TRUONGDV
	 * Date : 09/11/2012
	 * Idea : Doc template WORD và xuất ra file WORD
	 */ 
	public function createreportword($arrParameter){
		//Lay params
		$sPathXmlFile = $arrParameter['sPathXmlFile'];
		$sParrentTagName = $arrParameter['sParrentTagName'];
		$TagName = $arrParameter['TagName'];
		$dirTemplate = $arrParameter['sPathTemplateFile'].$arrParameter['sTemplateFile'].'.docx';
		//Goi class xu ly
		Zend_Loader::loadClass('Zend_Config_Xml');
		Zend_Loader::loadClass('Efy_phpDocx');
		//Tao doi tuong
		$ojbConfigXml = new Zend_Config_Xml($sPathXmlFile);
		$phpdocx = new Efy_phpDocx($dirTemplate);
		//Lay tieu chi tim kiem
		$arrFilter = $ojbConfigXml->table_struct_of_filter_form->filter_row->toArray();
		$arrFilterValue = $arrParameter['arrFilterValue'];
		$arrTagFilter = $this->getDataFilter($arrFilter,$arrFilterValue);
		//Lay chuoi sql và replace
		$sql = $ojbConfigXml->report_sql->sql;
		$data = $this->getAllData($sql,$arrTagFilter);
		$phpdocx->assignToHeader("#HEADER1#","Header 1"); // basic field mapping to header
		$phpdocx->assignToFooter("#FOOTER1#","Footer 1"); // basic field mapping to footer
		//Header
		$arrHeader = $ojbConfigXml->report_header->col->toArray();
		if(is_array($arrHeader)){
			foreach ($arrHeader as $key => $arrElement) {
				$field_name 	= $arrElement['field_name'];
				$row 			= $arrElement['row'];
				$field_column 	= $arrElement['field_column'];
				$replace 		= $arrElement['replace'];
				$type 			= $arrElement['type'];
				switch ($type) {
					case 'function':
						$params = $arrElement['param'];
						$arrParams = explode(',', $params);
						$phpFunction = $arrElement['phpFunction'];
						$pClassname = $arrElement['classname'];
						$i =0;
						$arrParamFunc = array();
						foreach ($arrParams as $key => $param) {
							if(isset($arrFilterValue[$param])){
								$arrParamFunc[] = $arrFilterValue[$param];
							}else {
								$arrParamFunc[] = $param;
							}
							$i++;
						}
						$objClass = new $pClassname;
						$value = $objClass->$phpFunction($arrParamFunc);
						break;
					
					default:
						$value = $arrFilterValue[$replace];
						break;
				}
				$phpdocx->assign('#'.$field_column.'#',$value);
			}
		}
		$arrDocx = array();
		$level1groupid = $ojbConfigXml->report_sql->level1groupid;
		$level1groupname = $ojbConfigXml->report_sql->level1groupname;
		$merge_col_from = $ojbConfigXml->report_sql->merge_col_from;
		if(isset($ojbConfigXml->report_body)){
			$TagElements = $ojbConfigXml->report_body->col_list->col->toArray();
			$arrBlock = array();
			$count = 0;
			$stt = 0;
			$default ='';
			$defaultName='';
			if(is_array($data)){
				foreach($data as $r => $dataRow) {
					$arrTemp = array();
					if($level1groupid !=''){
						if($dataRow[$level1groupid] != $default){
							$count = 0;
							$default = $dataRow[$level1groupid];
							$defaultName = $dataRow[$level1groupname];
							array_push($arrBlock, array('content'=>array(array('#'.$merge_col_from.'#'=>$defaultName)),'group'=>array('blockname'=>$r+1)));
						}
					}
					$count++;
					//Duyet cac phan tu cua	
			        foreach ($TagElements as $elements => $arrElement){
			           	$field_name 	= $arrElement['field_name'];
			           	$field_column 	= $arrElement['field_column'];
			           	$data_format	= $arrElement['data_format'];
			           	if($data_format =='identity'){
			           		$arrTemp['#'.$field_name.'#'] = $count;
		               	}else{
			           		$arrTemp['#'.$field_name.'#'] = $dataRow[$field_column];
			           	}
			        }
			        array_push($arrDocx, $arrTemp);
				}
		        $phpdocx->assignBlock("blockname",$arrDocx);
		        //Group
		        if($level1groupid !=''){
			        foreach ($arrBlock as $key => $value) {
			        	$phpdocx->assignNestedBlock("blockgroup",$value['content'],$value['group']);
			        }
		        }
		    }
		}
		//var_dump($arrDocx); die();
		$fileName = "nv01".date('dmy').date('His').".doc";
		// Duong dan file report
		$path = $_SERVER['SCRIPT_FILENAME'];
		$path = substr($path, 0, -9);
		$reportFile = str_replace("/", "\\", $path) . "public\\export\\" . $fileName;
		$phpdocx->save($reportFile);
		return $fileName;
	}
	public function getDate(){
		$date = date('d/m/Y');
		$arrDate = explode('/', $date);
		$string = 'ngày '.$arrDate['0'].' tháng '.$arrDate['1'].' năm '.$arrDate['2'];
		return $string;
	}
	/**
	 * Creater :TRUONGDV
	 * Date : 05/12/2012
	 * Idea : Xuat file word in thong tin qua trinh cai chinh
	 */ 
	public function createreportrecordchange($dirTemplate,$data){
		//Goi class xu ly
		Zend_Loader::loadClass('Efy_phpDocx');
		//Zend_Loader::loadClass('Efy_rtf');
		//Tao doi tuong
		$phpdocx = new Efy_phpDocx($dirTemplate);
		$phpdocx->assignToHeader("#HEADER1#","Header 1"); // basic field mapping to header
		$phpdocx->assignToFooter("#FOOTER1#","Footer 1"); // basic field mapping to footer
		$arrDocx = array();
		$count = 0;
		//utf8_uri_encode($utf8_string, $length = 0)
		if(is_array($data)){
			foreach($data as $r => $dataRow) {
				$arrTemp = array();
				$count++;
				/*$rtf = new Efy_rtf();
				$rtf->addText($dataRow['C_CONTENT']);
				//$rtf->parseDocument();
				$html =  '<p>A <span style="font-weight: bold" >very simple</span> HTML example.</p>';
				//$rtf = new rtf("rtf_config.php");
				$rtf->setPaperSize(5);
				$rtf->setPaperOrientation(1);
				$rtf->setDefaultFontFace(0);
				$rtf->setDefaultFontSize(20);
				$rtf->setAuthor("Obby");
				$rtf->setOperator("solor.motor@gmail.com");
				$rtf->setTitle("RTF Document");
				$rtf->addColour("#000000");
				$rtf->addText($dataRow['C_CONTENT']);
				echo $rtf->getDocument();
				die();*/

				$arrTemp = array('#A#'=>$count,
		        	'#B#'=>$dataRow['C_DATE'],
		        	'#C#'=>Efy_Publib_Library::_replaceBadChar($dataRow['C_CONTENT']),
		        	'#D#'=>$dataRow['C_SUBJECT'],
		        	'#E#'=>$dataRow['C_CREATER_POSITION_NAME']
		        	);
		        array_push($arrDocx, $arrTemp);
			}
	        $phpdocx->assignBlock("blockname",$arrDocx);
	    }
		//var_dump($arrDocx); die();
		$fileName = "nv01".date('dmy').date('His').".doc";
		// Duong dan file report
		$path = $_SERVER['SCRIPT_FILENAME'];
		$path = substr($path, 0, -9);
		$reportFile = str_replace("/", "\\", $path) . "public\\export\\" . $fileName;
		$phpdocx->save($reportFile);
		return $fileName;
	}

	/**
	 * Creater:TRUONGDV
	 * Date: 13/12/2012
	 * Idea: Doc temp html xuat ra file word dua vao cac tieu tri trong file xml
	 * Param: - sPathXmlFile: Đường dẫn lưu file xml
	 *		  - arrFilterValue: Mảng lưu tiêu chí lọc phục vụ cho lấy dữ liệu
	 *		  - fileTemplate : Đường dẫn lưu file template
	 */ 
	public function exportDecision($arrParameter){
		$objEfyLib = new  Efy_Library();
		//Lay params
		$sPathXmlFile = $arrParameter['sPathXmlFile'];
		//Goi class xu ly
		Zend_Loader::loadClass('Zend_Config_Xml');
		//Tao doi tuong
		$ojbConfigXml = new Zend_Config_Xml($sPathXmlFile);
		//Lay tieu chi tim kiem
		$arrFilter = $ojbConfigXml->table_struct_of_filter_form->filter_row->toArray();
		$arrFilterValue = $arrParameter['arrFilterValue'];
		$arrTagFilter = $this->getDataFilter($arrFilter,$arrFilterValue);
		//Lay chuoi sql và replace
		$sql = $ojbConfigXml->report_sql->sql;
		$data = $this->getAllData($sql,$arrTagFilter,1);
		//var_dump($data); die();
		//Header
		$arrBody = $ojbConfigXml->report_body->col->toArray();
		//Doc file template
		$contenFile = Efy_Publib_Library::_readFile($arrParameter['fileTemplate']);

		if(is_array($arrBody)){
			foreach ($arrBody as $key => $arrElement) {
				$field_column 	= $arrElement['field_column'];
				$replace 		= $arrElement['replace'];
				$type 			= $arrElement['type'];
				switch ($type) {
					case 'function':
						$params = $arrElement['param'];
						$arrParams = explode(',', $params);
						$phpFunction = $arrElement['phpFunction'];
						$pClassname = $arrElement['classname'];
						$i =0;
						$arrParamFunc = array();
						foreach ($arrParams as $key => $param) {
							if(isset($data[$param])){
								$arrParamFunc[] = $data[$param];
							}else {
								$arrParamFunc[] = $param;
							}
							$i++;
						}
						$objClass = new $pClassname;
						$value = $objClass->$phpFunction($arrParamFunc);
						break;
					
					default:
						$value = $data[$replace];
						break;
				}
				$contenFile = str_replace('#'.$field_column.'#',$value,$contenFile);
				
			}
		}
		$v_filename = "giay_in_quyet_dinh_".date('dmy').date('His').".doc";
		$ouptut = realpath('public/export/').'/'.$v_filename;
		//Ghi ra file
		$objEfyLib->_writeFile($ouptut,$contenFile);
		return $v_filename;
	}
	/**
	 * Hàm convert trong xml
	 * Convert 'XÃ KIM THÀNH' => 'xã Kim Thành'
	 */
	public function convertUnitUpper($arrInput){
		$district = (string)$arrInput['0'];
		$district = mb_strtolower($district,'UTF-8');
		$arrDistrict = explode(' ', $district);
		for ($i=1; $i < sizeof($arrDistrict) ; $i++) { 
			$arrDistrict[$i] = ucwords($arrDistrict[$i]);
		}
		$district = implode(' ', $arrDistrict);
		return $district;
	}
	public static function loadCache($type){
		Zend_Loader::loadClass('Zend_Cache');	
		$pFilePath = Efy_Init_Config::_setCacheUrlPath();
		$frontendParam=array(
           //  'lifetime'=>3600,        //thời gian tồn tại của cache, giá trị null nghĩa là thời gian tồn tại vô hạn
           'automatic_serialization'=>'true' //cho phép tự động serialize với các kiểu dữ liệu phức tạp
        );
        $backendParam = array(
            'cache_dir' => $pFilePath//
        );
		$cache = Zend_Cache::factory('Core','File',$frontendParam,$backendParam);//khởi tạo một đối tượng $cache với cache frontend là Core, cache backend là File cùng các thông số tương ứng
		//backend là File cùng các thông số tương ứng
		return $cache->load($type);
	}
	/**
	 * Hàm convert trong xml
	 * Convert chữ cái đầu tiên của chuỗi thành: - Chữ hoa nếu $arrInput[1] = 1
	 *											- Chữ thường nếu $arrInput[1] = 0
	 */
	public function convertAbridgment($arrInput){
		$abridgemnt = (string)$arrInput['0'];
		$option = (string)$arrInput['1'];
		if($option == '1'){
			$abridgemnt[0] = ucwords($abridgemnt[0]);
		}else{
			$abridgemnt[0] = mb_strtolower($abridgemnt[0],'UTF-8');
		}
		return $abridgemnt;
	}
	/*
	 * @creater: Phuongtt
	 * @date: 10/01/2013
	 * @des: Ham update file trong database
	 * @params:   $tableName : Ten bang chua ban ghi co file dinh kem
	 			  $pkName	 : Ten cot pk cua bang $tableName
				  $recordId  : Id cua ban ghi can cap nhat file dinh kem
				  $docType   : Loai file dinh kem (C_DOCTYPE trong bang t_efylib_file)					  
	 */
	public function UpdateFileInDB($tableName, $pkName, $recordId, $docType, $fileNameList){
		$objConn = new  Efy_DB_Connection(); 
		$sql = "mTL_UpdateFileAttach ";
		$sql = $sql . "'" . $recordId . "'";
		$sql = $sql . ",'" . $fileNameList . "'";
		$sql = $sql . ",'" . $docType . "'";
		$sql = $sql . ",'" . $tableName . "'";
		$sql = $sql . ",'" . $pkName . "'";		
		//echo $sql;		
		try {						
			$arrResult = $objConn->adodbExecSqlString($sql);					
		}catch (Exception $e){
			echo $e->getMessage();
		};					
	}
	/*
	 * @creater: Phuongtt
	 * @date: 10/01/2013
	 * @des: Ham update file trong database
	 * @params:   $tableName : Ten bang chua ban ghi co file dinh kem
	 			  $pkName	 : Ten cot pk cua bang $tableName
				  $recordId  : Id cua ban ghi can cap nhat file dinh kem
				  $docType   : Loai file dinh kem (C_DOCTYPE trong bang t_efylib_file)					  
	 */
	public function DelFileInDB($tableName, $pkName, $recordId, $docType, $fileNameList){
		$objConn = new  Efy_DB_Connection(); 
		$sql = "mTL_DeleteFileAttach ";
		$sql = $sql . "'" . $recordId . "'";
		$sql = $sql . ",'" . $fileNameList . "'";
		$sql = $sql . ",'" . $docType . "'";
		$sql = $sql . ",'" . $tableName . "'";
		$sql = $sql . ",'" . $pkName . "'";		
		//echo $sql;
		try {						
			$arrResult = $objConn->adodbExecSqlString($sql);					
		}catch (Exception $e){
			echo $e->getMessage();
		};					
	}	
	public function genLeftTree(){
		return '
			<div id = "left-silebar">
				<div>
					<div class = "search-tree">
						<input type="text" value="" autocomplete="off" class="textbox" id = "searchNodes" name = "searchNodes">
						<input type = "button" class = "link-button clsearch" load="true" id = "searchNode">
					</div>
					<div id = "left_tree"></div>			
					<div id = "push-left">
						<div id ="push-left-img" onclick = "left_menu_hide();"></div>
					</div>				
				</div>
			</div>
			<div id = "push-left-hide">
				<div id ="push-left-img-hide" onclick = "left_menu_show();"></div>
			</div>';
	}
	public function genbreadcrumbs($pk_tree){
		$objEfyDBConnection = new Efy_DB_Connection();
		$arrResul = $objEfyDBConnection->EfyLibQueryDb(array('pk_tree' => $pk_tree), 'mTL_getSubParentNode', true);
		$breadcrumb = '';
		if($arrResul){
			$iTotal = sizeof($arrResul);
			$breadcrumb .='<ul>';
			for ($i=$iTotal-1; $i >=0 ; $i--) { 
				if($i > 0)
					$text = $arrResul[$i]['C_NAME'] .'<span>></span>';
				else
					$text = $arrResul[$i]['C_NAME'];
				$breadcrumb .= '<li class="alowclick alck" pktree="'.$arrResul[$i]['PK_TREE'].'">'. $text.'</li>';
			}
			$breadcrumb .='</ul>';
		}
		return $breadcrumb;
	}

	public  function uploadDocument($listUrlAttach, $sDir, $sDelimitor = "!~~!")
	{
		$path = self::_createFolder($sDir,date('Y'),date('m'),date('d'));
		$sFileNameList = "";		
		$arrUrlAttach=explode($sDelimitor,$listUrlAttach);
		$count=sizeof($arrUrlAttach);
		if($count==0){
			return $sFileNameList;
		}
		for ($i=0; $i < $count; $i++) {
			$urlTemp = '..'.$arrUrlAttach[$i];
			$arr = explode('!~!', $urlTemp);
			$filename = end($arr);
			$random = self::_get_randon_number();
			$fodel = date("Y").'_'.date("m").'_'.date("d")."_".date("H").date("i").date("u").$random."!~!";
			$sFullFileName = $fodel. $filename;	
			$dest = $path . self::_convertVNtoEN($sFullFileName);
			//Di chuyen sang thu muc luu tru
			if(file_exists($urlTemp)){
				copy($urlTemp, $dest);
				// convert flash
				$program = Efy_Init_Config::getInstance()->getProgramPrint2Flash();
				$cmd = $program.' "'.realpath($dest).'" "'.realpath($dest).'.swf"';
				$output = shell_exec($cmd);
				//Xoa file o thu muc tam
				unlink($urlTemp);
			}				
			$sFileNameList .= $sFullFileName . $sDelimitor;
		}
		$sFileNameList = substr($sFileNameList,0,strlen($sFileNameList) - strlen($sDelimitor));
		// tra lai gia tri			
		return self::_convertVNtoEN($sFileNameList);			
	}
 }	